code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:widgetbook/src/rendering/builders/text_scale_builder.dart';
import 'package:widgetbook/src/rendering/rendering.dart';
import 'package:widgetbook_models/widgetbook_models.dart';
void main() {
group(
'$RenderingProvider',
() {
test(
'sets state',
() {
final frames = [
WidgetbookFrame.defaultFrame(),
WidgetbookFrame.noFrame(),
];
final deviceFrameBuilder = defaultDeviceFrameBuilder;
final localizationBuilder = defaultLocalizationBuilder;
final themeBuilder = defaultThemeBuilder<ThemeData>();
final scaffoldBuilder = defaultScaffoldBuilder;
final useCaseBuilder = defaultUseCaseBuilder;
final textScaleBuilder = defaultTextScaleBuilder;
final provider = RenderingProvider(
frames: frames,
deviceFrameBuilder: deviceFrameBuilder,
localizationBuilder: localizationBuilder,
themeBuilder: themeBuilder,
scaffoldBuilder: scaffoldBuilder,
useCaseBuilder: useCaseBuilder,
textScaleBuilder: textScaleBuilder,
);
expect(
provider.state,
equals(
RenderingState(
frames: frames,
deviceFrameBuilder: deviceFrameBuilder,
localizationBuilder: localizationBuilder,
themeBuilder: themeBuilder,
scaffoldBuilder: scaffoldBuilder,
textScaleBuilder: textScaleBuilder,
useCaseBuilder: useCaseBuilder,
),
),
);
},
);
},
);
}
| widgetbook/packages/widgetbook/test/src/rendering/rendering_provider_test.dart/0 | {'file_path': 'widgetbook/packages/widgetbook/test/src/rendering/rendering_provider_test.dart', 'repo_id': 'widgetbook', 'token_count': 781} |
import 'package:flutter/material.dart';
import 'package:widgetbook_device_frame/src/info/device_type.dart';
import 'package:widgetbook_device_frame/src/info/identifier.dart';
import 'package:widgetbook_device_frame/src/info/info.dart';
part 'frame.g.dart';
part 'screen.g.dart';
final info = DeviceInfo(
identifier: const DeviceIdentifier(
TargetPlatform.android,
DeviceType.phone,
'samsung-galaxy-note20',
),
name: 'Samsung Galaxy Note 20',
pixelRatio: 2.625,
safeAreas: const EdgeInsets.only(
left: 0.0,
top: 48.0,
right: 0.0,
bottom: 32.0,
),
rotatedSafeAreas: const EdgeInsets.only(
left: 48.0,
top: 24.0,
right: 48.0,
bottom: 0.0,
),
framePainter: const _FramePainter(),
screenPath: _screenPath,
frameSize: const Size(834, 1788.93),
screenSize: const Size(412.0, 916.0),
);
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20/device.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20/device.dart', 'repo_id': 'widgetbook', 'token_count': 341} |
import 'package:flutter/material.dart';
import 'package:widgetbook_device_frame/src/devices/generic/base/draw_extensions.dart';
import 'package:widgetbook_device_frame/src/info/device_type.dart';
import 'package:widgetbook_device_frame/src/info/identifier.dart';
import 'package:widgetbook_device_frame/src/info/info.dart';
part 'frame.dart';
/// Creates a generic laptop device definition.
DeviceInfo buildGenericLaptopDevice({
required TargetPlatform platform,
required String id,
required String name,
required Size screenSize,
required Rect windowPosition,
EdgeInsets safeAreas = EdgeInsets.zero,
double pixelRatio = 2.0,
EdgeInsets? rotatedSafeAreas,
GenericLaptopFramePainter? framePainter,
}) {
final effectivePainter = framePainter ??
GenericLaptopFramePainter(
platform: platform,
windowPosition: windowPosition,
);
return DeviceInfo(
identifier: DeviceIdentifier(
platform,
DeviceType.laptop,
id,
),
name: name,
pixelRatio: pixelRatio,
frameSize: effectivePainter.calculateFrameSize(screenSize),
screenSize: effectivePainter.effectiveWindowSize,
safeAreas: safeAreas,
rotatedSafeAreas: rotatedSafeAreas,
framePainter: effectivePainter,
screenPath: effectivePainter.createScreenPath(screenSize),
);
}
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/generic/laptop/device.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/generic/laptop/device.dart', 'repo_id': 'widgetbook', 'token_count': 444} |
import 'package:flutter/material.dart';
import 'package:widgetbook_device_frame/src/info/device_type.dart';
import 'package:widgetbook_device_frame/src/info/identifier.dart';
import 'package:widgetbook_device_frame/src/info/info.dart';
part 'frame.g.dart';
part 'screen.g.dart';
final info = DeviceInfo(
identifier: const DeviceIdentifier(
TargetPlatform.iOS,
DeviceType.phone,
'iphone-12',
),
name: 'iPhone 12',
pixelRatio: 3.0,
frameSize: const Size(873.0, 1771.0),
screenSize: const Size(390.0, 844.0),
safeAreas: const EdgeInsets.only(
left: 0.0,
top: 44.0,
right: 0.0,
bottom: 34.0,
),
rotatedSafeAreas: const EdgeInsets.only(
left: 44.0,
top: 0.0,
right: 44.0,
bottom: 21.0,
),
framePainter: const _FramePainter(),
screenPath: _screenPath,
);
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_12/device.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_12/device.dart', 'repo_id': 'widgetbook', 'token_count': 337} |
// 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(866.809, 495.105);
path_0.lineTo(869.904, 495.105);
path_0.cubicTo(871.614, 495.105, 873, 496.49, 873, 498.199);
path_0.lineTo(873, 683.864);
path_0.cubicTo(873, 685.573, 871.614, 686.958, 869.904, 686.958);
path_0.lineTo(866.809, 686.958);
path_0.lineTo(866.809, 495.105);
path_0.close();
final paint_0_fill = Paint()..style = PaintingStyle.fill;
paint_0_fill.color = const Color(0xff213744);
canvas.drawPath(path_0, paint_0_fill);
final path_1 = Path();
path_1.moveTo(6.19141, 728.217);
path_1.lineTo(3.09565, 728.217);
path_1.cubicTo(1.38592, 728.217, 0, 726.831, 0, 725.122);
path_1.lineTo(0, 609.598);
path_1.cubicTo(0, 607.889, 1.38593, 606.503, 3.09566, 606.503);
path_1.lineTo(6.19142, 606.503);
path_1.lineTo(6.19141, 728.217);
path_1.close();
final paint_1_fill = Paint()..style = PaintingStyle.fill;
paint_1_fill.color = const Color(0xff213744);
canvas.drawPath(path_1, paint_1_fill);
final path_2 = Path();
path_2.moveTo(6.19141, 573.496);
path_2.lineTo(3.09565, 573.496);
path_2.cubicTo(1.38592, 573.496, 0, 572.111, 0, 570.402);
path_2.lineTo(0, 454.877);
path_2.cubicTo(0, 453.168, 1.38593, 451.783, 3.09566, 451.783);
path_2.lineTo(6.19142, 451.783);
path_2.lineTo(6.19141, 573.496);
path_2.close();
final paint_2_fill = Paint()..style = PaintingStyle.fill;
paint_2_fill.color = const Color(0xff213744);
canvas.drawPath(path_2, paint_2_fill);
final path_3 = Path();
path_3.moveTo(6.19141, 398.147);
path_3.lineTo(3.09566, 398.147);
path_3.cubicTo(1.38592, 398.147, 0, 396.761, 0, 395.052);
path_3.lineTo(0, 343.479);
path_3.cubicTo(0, 341.77, 1.38593, 340.384, 3.09566, 340.384);
path_3.lineTo(6.19141, 340.384);
path_3.lineTo(6.19141, 398.147);
path_3.close();
final paint_3_fill = Paint()..style = PaintingStyle.fill;
paint_3_fill.color = const Color(0xff213744);
canvas.drawPath(path_3, paint_3_fill);
final path_4 = Path();
path_4.moveTo(6.19141, 187.727);
path_4.cubicTo(6.19141, 137.811, 6.19141, 112.853, 12.7571, 92.6545);
path_4.cubicTo(26.0269, 51.8322, 58.046, 19.8269, 98.886, 6.56288);
path_4.cubicTo(119.093, 0, 144.062, 0, 194, 0);
path_4.lineTo(679, 0);
path_4.cubicTo(728.938, 0, 753.907, 0, 774.114, 6.56288);
path_4.cubicTo(814.954, 19.8269, 846.973, 51.8322, 860.243, 92.6545);
path_4.cubicTo(866.808, 112.853, 866.808, 137.811, 866.808, 187.727);
path_4.lineTo(866.808, 1582.27);
path_4.cubicTo(866.808, 1632.19, 866.808, 1657.15, 860.243, 1677.35);
path_4.cubicTo(846.973, 1718.17, 814.954, 1750.17, 774.114, 1763.44);
path_4.cubicTo(753.907, 1770, 728.938, 1770, 679, 1770);
path_4.lineTo(194, 1770);
path_4.cubicTo(144.062, 1770, 119.093, 1770, 98.886, 1763.44);
path_4.cubicTo(58.046, 1750.17, 26.0269, 1718.17, 12.7571, 1677.35);
path_4.cubicTo(6.19141, 1657.15, 6.19141, 1632.19, 6.19141, 1582.27);
path_4.lineTo(6.19141, 187.727);
path_4.close();
final paint_4_fill = Paint()..style = PaintingStyle.fill;
paint_4_fill.color = const Color(0xff213744);
canvas.drawPath(path_4, paint_4_fill);
final path_5 = Path();
path_5.moveTo(679.824, 4.12593);
path_5.lineTo(193.173, 4.12593);
path_5.cubicTo(143.843, 4.12593, 119.667, 4.15138, 100.16, 10.4869);
path_5.cubicTo(60.5768, 23.3427, 29.5429, 54.3633, 16.6814, 93.9296);
path_5.cubicTo(10.3432, 113.428, 10.3177, 137.593, 10.3177, 186.902);
path_5.lineTo(10.3177, 1583.1);
path_5.cubicTo(10.3177, 1632.41, 10.3432, 1656.57, 16.6814, 1676.07);
path_5.cubicTo(29.5429, 1715.64, 60.5768, 1746.66, 100.16, 1759.51);
path_5.cubicTo(119.667, 1765.85, 143.843, 1765.87, 193.173, 1765.87);
path_5.lineTo(679.824, 1765.87);
path_5.cubicTo(729.154, 1765.87, 753.33, 1765.85, 772.837, 1759.51);
path_5.cubicTo(812.42, 1746.66, 843.454, 1715.64, 856.316, 1676.07);
path_5.cubicTo(862.654, 1656.57, 862.679, 1632.41, 862.679, 1583.1);
path_5.lineTo(862.679, 186.902);
path_5.cubicTo(862.679, 137.593, 862.654, 113.428, 856.316, 93.9296);
path_5.cubicTo(843.454, 54.3633, 812.42, 23.3427, 772.837, 10.4869);
path_5.cubicTo(753.33, 4.15138, 729.154, 4.12593, 679.824, 4.12593);
path_5.close();
path_5.moveTo(14.7186, 93.2921);
path_5.cubicTo(8.25391, 113.18, 8.25391, 137.754, 8.25391, 186.902);
path_5.lineTo(8.25391, 1583.1);
path_5.cubicTo(8.25391, 1632.25, 8.25391, 1656.82, 14.7186, 1676.71);
path_5.cubicTo(27.7842, 1716.9, 59.3107, 1748.42, 99.5225, 1761.48);
path_5.cubicTo(119.419, 1767.94, 144.004, 1767.94, 193.173, 1767.94);
path_5.lineTo(679.824, 1767.94);
path_5.cubicTo(728.994, 1767.94, 753.578, 1767.94, 773.475, 1761.48);
path_5.cubicTo(813.686, 1748.42, 845.213, 1716.9, 858.279, 1676.71);
path_5.cubicTo(864.743, 1656.82, 864.743, 1632.25, 864.743, 1583.1);
path_5.lineTo(864.743, 186.902);
path_5.cubicTo(864.743, 137.754, 864.743, 113.18, 858.279, 93.2921);
path_5.cubicTo(845.213, 53.0977, 813.686, 21.5848, 773.475, 8.5249);
path_5.cubicTo(753.578, 2.06299, 728.994, 2.06299, 679.824, 2.06299);
path_5.lineTo(193.173, 2.06299);
path_5.cubicTo(144.004, 2.06299, 119.419, 2.06299, 99.5225, 8.5249);
path_5.cubicTo(59.3107, 21.5848, 27.7842, 53.0977, 14.7186, 93.2921);
path_5.close();
final paint_5_fill = Paint()..style = PaintingStyle.fill;
paint_5_fill.color = const Color(0xff8EADC1);
canvas.drawPath(path_5, paint_5_fill);
final path_6 = Path();
path_6.moveTo(16.5117, 183.601);
path_6.cubicTo(16.5117, 137.525, 16.5117, 114.487, 22.5724, 95.842);
path_6.cubicTo(34.8214, 58.1598, 64.3775, 28.6164, 102.076, 16.3727);
path_6.cubicTo(120.729, 10.3147, 143.777, 10.3147, 189.873, 10.3147);
path_6.lineTo(683.129, 10.3147);
path_6.cubicTo(729.225, 10.3147, 752.273, 10.3147, 770.926, 16.3727);
path_6.cubicTo(808.625, 28.6164, 838.181, 58.1598, 850.43, 95.842);
path_6.cubicTo(856.49, 114.487, 856.49, 137.525, 856.49, 183.601);
path_6.lineTo(856.49, 1586.4);
path_6.cubicTo(856.49, 1632.48, 856.49, 1655.51, 850.43, 1674.16);
path_6.cubicTo(838.181, 1711.84, 808.625, 1741.38, 770.926, 1753.63);
path_6.cubicTo(752.273, 1759.69, 729.225, 1759.69, 683.129, 1759.69);
path_6.lineTo(189.873, 1759.69);
path_6.cubicTo(143.777, 1759.69, 120.729, 1759.69, 102.076, 1753.63);
path_6.cubicTo(64.3775, 1741.38, 34.8214, 1711.84, 22.5724, 1674.16);
path_6.cubicTo(16.5117, 1655.51, 16.5117, 1632.48, 16.5117, 1586.4);
path_6.lineTo(16.5117, 183.601);
path_6.close();
final paint_6_fill = Paint()..style = PaintingStyle.fill;
paint_6_fill.color = const Color(0xff121515);
canvas.drawPath(path_6, paint_6_fill);
final path_7 = Path();
path_7.moveTo(683.127, 0);
path_7.lineTo(695.51, 0);
path_7.lineTo(695.51, 10.3147);
path_7.lineTo(683.127, 10.3147);
path_7.lineTo(683.127, 0);
path_7.close();
final paint_7_fill = Paint()..style = PaintingStyle.fill;
paint_7_fill.color = const Color(0xff36454C);
canvas.drawPath(path_7, paint_7_fill);
final path_8 = Path();
path_8.moveTo(856.49, 177.413);
path_8.lineTo(866.809, 177.413);
path_8.lineTo(866.809, 189.79);
path_8.lineTo(856.49, 189.79);
path_8.lineTo(856.49, 177.413);
path_8.close();
final paint_8_fill = Paint()..style = PaintingStyle.fill;
paint_8_fill.color = const Color(0xff36454C);
canvas.drawPath(path_8, paint_8_fill);
final path_9 = Path();
path_9.moveTo(6.19141, 177.413);
path_9.lineTo(16.5106, 177.413);
path_9.lineTo(16.5106, 189.79);
path_9.lineTo(6.19141, 189.79);
path_9.lineTo(6.19141, 177.413);
path_9.close();
final paint_9_fill = Paint()..style = PaintingStyle.fill;
paint_9_fill.color = const Color(0xff36454C);
canvas.drawPath(path_9, paint_9_fill);
final path_10 = Path();
path_10.moveTo(6.19141, 1580.21);
path_10.lineTo(16.5106, 1580.21);
path_10.lineTo(16.5106, 1592.59);
path_10.lineTo(6.19141, 1592.59);
path_10.lineTo(6.19141, 1580.21);
path_10.close();
final paint_10_fill = Paint()..style = PaintingStyle.fill;
paint_10_fill.color = const Color(0xff36454C);
canvas.drawPath(path_10, paint_10_fill);
final path_11 = Path();
path_11.moveTo(856.49, 1580.21);
path_11.lineTo(866.809, 1580.21);
path_11.lineTo(866.809, 1592.59);
path_11.lineTo(856.49, 1592.59);
path_11.lineTo(856.49, 1580.21);
path_11.close();
final paint_11_fill = Paint()..style = PaintingStyle.fill;
paint_11_fill.color = const Color(0xff36454C);
canvas.drawPath(path_11, paint_11_fill);
final path_12 = Path();
path_12.moveTo(177.49, 1759.69);
path_12.lineTo(189.873, 1759.69);
path_12.lineTo(189.873, 1770);
path_12.lineTo(177.49, 1770);
path_12.lineTo(177.49, 1759.69);
path_12.close();
final paint_12_fill = Paint()..style = PaintingStyle.fill;
paint_12_fill.color = const Color(0xff36454C);
canvas.drawPath(path_12, paint_12_fill);
final path_13 = Path();
path_13.moveTo(331.447, 73.8811);
path_13.cubicTo(339.426, 73.8811, 345.894, 67.4159, 345.894, 59.4406);
path_13.cubicTo(345.894, 51.4653, 339.426, 45, 331.447, 45);
path_13.cubicTo(323.468, 45, 317, 51.4653, 317, 59.4406);
path_13.cubicTo(317, 67.4159, 323.468, 73.8811, 331.447, 73.8811);
path_13.close();
final paint_13_fill = Paint()..style = PaintingStyle.fill;
paint_13_fill.color = const Color(0xff262C2D);
canvas.drawPath(path_13, paint_13_fill);
final path_14 = Path();
path_14.moveTo(331.447, 68.466);
path_14.cubicTo(336.434, 68.466, 340.476, 64.4252, 340.476, 59.4406);
path_14.cubicTo(340.476, 54.4561, 336.434, 50.4153, 331.447, 50.4153);
path_14.cubicTo(326.46, 50.4153, 322.418, 54.4561, 322.418, 59.4406);
path_14.cubicTo(322.418, 64.4252, 326.46, 68.466, 331.447, 68.466);
path_14.close();
final paint_14_fill = Paint()..style = PaintingStyle.fill;
paint_14_fill.color = const Color(0xff121515);
canvas.drawPath(path_14, paint_14_fill);
final path_15 = Path();
path_15.moveTo(331.446, 57.6355);
path_15.cubicTo(332.444, 57.6355, 333.252, 56.8274, 333.252, 55.8305);
path_15.cubicTo(333.252, 54.8335, 332.444, 54.0254, 331.446, 54.0254);
path_15.cubicTo(330.449, 54.0254, 329.641, 54.8335, 329.641, 55.8305);
path_15.cubicTo(329.641, 56.8274, 330.449, 57.6355, 331.446, 57.6355);
path_15.close();
final paint_15_fill = Paint()..style = PaintingStyle.fill;
paint_15_fill.color = const Color(0xff636F73);
canvas.drawPath(path_15, paint_15_fill);
final path_16 = Path();
path_16.moveTo(372, 13);
path_16.lineTo(499, 13);
path_16.lineTo(499, 17);
path_16.cubicTo(499, 21.4183, 495.418, 25, 491, 25);
path_16.lineTo(380, 25);
path_16.cubicTo(375.582, 25, 372, 21.4183, 372, 17);
path_16.lineTo(372, 13);
path_16.close();
final paint_16_fill = Paint()..style = PaintingStyle.fill;
paint_16_fill.color = const Color(0xff262C2D);
canvas.drawPath(path_16, paint_16_fill);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
| widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_13_pro_max/frame.g.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_13_pro_max/frame.g.dart', 'repo_id': 'widgetbook', 'token_count': 5907} |
import 'package:flutter/material.dart';
import 'package:widgetbook_device_frame/widgetbook_device_frame.dart';
import 'button.dart';
/// Display a simulated on screen keyboard at the bottom of a [child] widget.
///
/// When [isEnabled] is updated, a [transitionDuration] starts to display
/// or hide the virtual keyboard.
///
/// No interraction is available, its only purpose is to display
/// the visual and update media query's `viewInsets` for [child].
class VirtualKeyboard extends StatelessWidget {
/// Display a simulated on screen keyboard on top of the given [child] widget.
///
/// When [isEnabled] is updated, a [transitionDuration] starts to display
/// or hide the virtual keyboard.
///
/// No interraction is available, its only purpose is to display
/// the visual and update media query's `viewInsets` for [child].
const VirtualKeyboard({
Key? key,
required this.child,
this.isEnabled = false,
this.transitionDuration = const Duration(milliseconds: 400),
}) : super(key: key);
/// Adds the keyboard insets to the given [mediaQuery].
static MediaQueryData mediaQuery(MediaQueryData mediaQuery) {
final insets = EdgeInsets.only(
bottom: _VirtualKeyboard.minHeight + mediaQuery.padding.bottom,
);
return mediaQuery.copyWith(
viewInsets: insets,
viewPadding: mediaQuery.viewPadding,
padding: mediaQuery.padding.copyWith(
bottom: 0,
),
);
}
/// Indicates whether the keyboard is displayed or not.
final bool isEnabled;
/// The widget on top of which the keyboard is displayed.
final Widget child;
/// The transition duration when the keyboard is displayed or hidden.
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return Stack(
children: <Widget>[
Positioned.fill(
child: MediaQuery(
data: !isEnabled
? mediaQuery
: VirtualKeyboard.mediaQuery(mediaQuery),
child: child,
),
),
Positioned(
bottom: -1,
left: -1,
right: -1,
child: AnimatedCrossFade(
firstChild: const SizedBox(),
secondChild: const _VirtualKeyboard(
height: _VirtualKeyboard.minHeight,
),
crossFadeState: isEnabled
? CrossFadeState.showSecond
: CrossFadeState.showFirst,
duration: transitionDuration,
),
),
],
);
}
}
class _VirtualKeyboard extends StatelessWidget {
const _VirtualKeyboard({
double? height,
this.spacing = 12,
}) : height = height ?? minHeight;
static const double minHeight = 214;
final double height;
final double spacing;
Widget _row(List<Widget> children) {
return Padding(
padding: EdgeInsets.only(
top: spacing,
left: spacing,
),
child: Row(
children: children,
),
);
}
List<Widget> _letters(
List<String> letters,
Color backgroundColor,
Color foregroundColor,
) {
return letters
.map<Widget>(
(x) => Expanded(
child: Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
backgroundColor: backgroundColor,
child: Text(
x,
style: TextStyle(
fontSize: 14,
color: foregroundColor,
),
),
),
),
),
)
.toList();
}
@override
Widget build(BuildContext context) {
final theme = DeviceFrameTheme.of(context).keyboardStyle;
final mediaQuery = MediaQuery.of(context);
return Container(
height: height + mediaQuery.padding.bottom,
padding: EdgeInsets.only(
left: mediaQuery.padding.left + 1,
right: mediaQuery.padding.right + 1,
),
color: theme.backgroundColor,
child: Column(
children: <Widget>[
_row(
_letters(
['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
theme.button1BackgroundColor,
theme.button1ForegroundColor,
),
),
_row(
_letters(
['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'],
theme.button1BackgroundColor,
theme.button1ForegroundColor,
),
),
_row([
Padding(
padding: const EdgeInsets.only(
right: 12,
),
child: VirtualKeyboardButton(
child: Icon(
Icons.keyboard_capslock,
color: theme.button2ForegroundColor,
size: 16,
),
backgroundColor: theme.button2BackgroundColor,
),
),
..._letters(
['Z', 'X', 'C', 'V', 'B', 'N', 'M'],
theme.button1BackgroundColor,
theme.button1ForegroundColor,
),
Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
child: Icon(
Icons.backspace,
color: theme.button2ForegroundColor,
size: 16,
),
backgroundColor: theme.button2BackgroundColor,
),
),
]),
_row(
[
Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
child: Text(
'123',
style: TextStyle(
fontSize: 14,
color: theme.button2ForegroundColor,
),
),
backgroundColor: theme.button2BackgroundColor,
),
),
Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
child: Icon(
Icons.insert_emoticon,
color: theme.button2ForegroundColor,
size: 16,
),
backgroundColor: theme.button2BackgroundColor,
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
child: Text(
'space',
style: TextStyle(
fontSize: 14,
color: theme.button2ForegroundColor,
),
),
backgroundColor: theme.button2BackgroundColor,
),
),
),
Padding(
padding: EdgeInsets.only(
right: spacing,
),
child: VirtualKeyboardButton(
child: Text(
'return',
style: TextStyle(
fontSize: 14,
color: theme.button2ForegroundColor,
),
),
backgroundColor: theme.button2BackgroundColor,
),
),
],
),
],
),
);
}
}
| widgetbook/packages/widgetbook_device_frame/lib/src/keyboard/virtual_keyboard.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/keyboard/virtual_keyboard.dart', 'repo_id': 'widgetbook', 'token_count': 4056} |
import 'package:meta/meta.dart';
import 'package:widgetbook_annotation/widgetbook_annotation.dart';
import 'package:widgetbook_generator/code_generators/instances/device_type_instance.dart';
import 'package:widgetbook_generator/code_generators/instances/instance.dart';
import 'package:widgetbook_generator/code_generators/instances/resolution_instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
@immutable
/// An instance of [Device]
class DeviceInstance extends Instance {
/// Creates a new instance of [DeviceInstance]
DeviceInstance({
required Device device,
}) : super(
name: 'Device',
properties: [
Property.string(
key: 'name',
value: device.name,
),
Property(
key: 'resolution',
instance: ResolutionInstance(
resolution: device.resolution,
),
),
Property(
key: 'type',
instance: DeviceTypeInstance(
deviceType: device.type,
),
),
],
);
}
| widgetbook/packages/widgetbook_generator/lib/code_generators/instances/device_instance.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/instances/device_instance.dart', 'repo_id': 'widgetbook', 'token_count': 511} |
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/widgetbook_widget_instance.dart';
import 'package:widgetbook_generator/code_generators/properties/property.dart';
import 'package:widgetbook_generator/services/tree_service.dart';
/// Defines an instance to create code for a [Folder]
class WidgetbookFolderInstance extends Instance {
/// Creates a new instance of [WidgetbookFolderInstance]
WidgetbookFolderInstance({required Folder folder})
: super(
name: 'WidgetbookFolder',
properties: [
Property.string(key: 'name', value: folder.name),
Property(
key: 'widgets',
instance: ListInstance<WidgetbookComponentInstance>(
instances: folder.widgets.values
.map(
(widget) => WidgetbookComponentInstance(
name: widget.name,
stories: widget.stories,
isExpanded: widget.isExpanded,
),
)
.toList(),
),
),
Property(
key: 'folders',
instance: ListInstance<WidgetbookFolderInstance>(
instances: folder.subFolders.values
.map((folder) => WidgetbookFolderInstance(folder: folder))
.toList(),
),
),
if (folder.isExpanded)
Property.bool(key: 'isExpanded', value: true),
],
);
}
| widgetbook/packages/widgetbook_generator/lib/code_generators/instances/widgetbook_folder_instance.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/instances/widgetbook_folder_instance.dart', 'repo_id': 'widgetbook', 'token_count': 811} |
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:widgetbook_generator/models/widgetbook_data.dart';
part 'widgetbook_device_frame_data.freezed.dart';
part 'widgetbook_device_frame_data.g.dart';
@freezed
class WidgetbookDeviceFrameData extends WidgetbookData
with _$WidgetbookDeviceFrameData {
factory WidgetbookDeviceFrameData({
required String name,
required String importStatement,
required List<String> dependencies,
}) = _WidgetbookDeviceFrameData;
factory WidgetbookDeviceFrameData.fromJson(Map<String, dynamic> json) =>
_$WidgetbookDeviceFrameDataFromJson(json);
}
| widgetbook/packages/widgetbook_generator/lib/models/widgetbook_device_frame_data.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/models/widgetbook_device_frame_data.dart', 'repo_id': 'widgetbook', 'token_count': 201} |
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:widgetbook_generator/models/widgetbook_data.dart';
part 'widgetbook_theme_builder_data.freezed.dart';
part 'widgetbook_theme_builder_data.g.dart';
@freezed
class WidgetbookThemeBuilderData extends WidgetbookData
with _$WidgetbookThemeBuilderData {
factory WidgetbookThemeBuilderData({
required String name,
required String importStatement,
required List<String> dependencies,
}) = _WidgetbookThemeBuilderData;
factory WidgetbookThemeBuilderData.fromJson(Map<String, dynamic> json) =>
_$WidgetbookThemeBuilderDataFromJson(json);
}
| widgetbook/packages/widgetbook_generator/lib/models/widgetbook_theme_builder_data.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/models/widgetbook_theme_builder_data.dart', 'repo_id': 'widgetbook', 'token_count': 201} |
import 'package:analyzer/dart/constant/value.dart';
import 'package:widgetbook_generator/readers/annotation_reader.dart';
import 'package:widgetbook_generator/readers/device_size_reader.dart';
import 'package:widgetbook_models/widgetbook_models.dart';
/// Parses [DartObject] into an object of type [Resolution]
class ResolutioReader extends AnnotationReader<Resolution> {
/// Creates a new object of [ResolutioReader]
///
/// [deviceSizeReader] defines a reader capable of parsing an [DartObject]
/// into [DeviceSize]
ResolutioReader({DeviceSizeReader? deviceSizeReader})
: deviceSizeReader = deviceSizeReader ?? DeviceSizeReader();
/// A reader capable of parsing an [DartObject] into [DeviceSize]
final DeviceSizeReader deviceSizeReader;
@override
Resolution read(DartObject object) {
final deviceSize = deviceSizeReader.read(
object.getField('nativeSize')!,
);
final scaleFactor = object.getField('scaleFactor')!.toDoubleValue()!;
return Resolution(
scaleFactor: scaleFactor,
nativeSize: deviceSize,
);
}
}
| widgetbook/packages/widgetbook_generator/lib/readers/resolution_reader.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/lib/readers/resolution_reader.dart', 'repo_id': 'widgetbook', 'token_count': 342} |
import 'package:test/test.dart';
import 'package:widgetbook_generator/code_generators/instances/instance.dart';
void testName(
String name, {
required Instance instance,
}) {
test(".name returns '$name'", () {
expect(
instance.name,
equals(name),
);
});
}
| widgetbook/packages/widgetbook_generator/test/src/code_generators/instance_helper.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instance_helper.dart', 'repo_id': 'widgetbook', 'token_count': 108} |
import 'package:test/expect.dart';
import 'package:test/scaffolding.dart';
import 'package:widgetbook_generator/code_generators/instances/variable_instance.dart';
void main() {
group(
'$VariableInstance',
() {
test(
'returns identifier',
() {
const variableId = 'test';
expect(
const VariableInstance(variableIdentifier: variableId).toCode(),
equals(variableId),
);
},
);
},
);
}
| widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/variable_instance.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/variable_instance.dart', 'repo_id': 'widgetbook', 'token_count': 218} |
import 'package:test/test.dart';
import 'package:widgetbook_models/src/devices/device_size.dart';
import 'package:widgetbook_models/src/devices/resolution.dart';
void main() {
group(
'$Resolution',
() {
test('returns Size(200, 200) when logicalSize is called', () {
final instance = Resolution.dimensions(
nativeHeight: 400,
nativeWidth: 400,
scaleFactor: 2,
);
expect(
instance.logicalSize,
equals(
const DeviceSize(
width: 200,
height: 200,
),
),
);
});
test(
'returns true when instance is the same',
() {
final instance = Resolution.dimensions(
nativeHeight: 1,
nativeWidth: 1,
scaleFactor: 1,
);
expect(
instance == instance,
equals(true),
);
},
);
group(
'returns true when',
() {
test(
'two instances with the same values are compared',
() {
final instance1 = Resolution.dimensions(
nativeHeight: 1,
nativeWidth: 1,
scaleFactor: 1,
);
final instance2 = Resolution.dimensions(
nativeHeight: 1,
nativeWidth: 1,
scaleFactor: 1,
);
expect(
instance1 == instance2,
equals(true),
);
},
);
test(
'the hashCodes of two instances with the same values are compared',
() {
final instance1 = Resolution.dimensions(
nativeHeight: 1,
nativeWidth: 1,
scaleFactor: 1,
);
final instance2 = Resolution.dimensions(
nativeHeight: 1,
nativeWidth: 1,
scaleFactor: 1,
);
expect(
instance1.hashCode == instance2.hashCode,
equals(true),
);
},
);
},
);
},
);
}
| widgetbook/packages/widgetbook_models/test/src/devices/resolution_test.dart/0 | {'file_path': 'widgetbook/packages/widgetbook_models/test/src/devices/resolution_test.dart', 'repo_id': 'widgetbook', 'token_count': 1251} |
import 'package:flutter/material.dart';
import 'package:widgetbook_challenge/form/views/widgets/name_form.dart';
/// The Form Page
class FormPage extends StatelessWidget {
/// Creates instance of the Form page
const FormPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Interview Challenge'),
),
body: const SingleChildScrollView(
padding: EdgeInsets.all(20),
child: NameForm(),
),
);
}
}
| widgetbook_challenge/lib/form/views/pages/form_page.dart/0 | {'file_path': 'widgetbook_challenge/lib/form/views/pages/form_page.dart', 'repo_id': 'widgetbook_challenge', 'token_count': 202} |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:widgetbook_challenge/app.dart';
import 'package:widgetbook_challenge/form/views/pages/form_page.dart';
void main() {
testWidgets('$App contains FormPage', (WidgetTester tester) async {
await tester.pumpWidget(App(key: UniqueKey()));
expect(find.byType(FormPage), findsOneWidget);
});
}
| widgetbook_challenge/test/app_test.dart/0 | {'file_path': 'widgetbook_challenge/test/app_test.dart', 'repo_id': 'widgetbook_challenge', 'token_count': 142} |
// Copyright (c) 2015, Anders Holmgren. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
library yamlicious.test;
import 'dart:io';
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';
import 'package:yamlicious/yamlicious.dart';
main() {
group("toYamlString", () {
test("roundtrip test", () {
var v = loadYaml(new File("test/example.yaml").readAsStringSync());
var s = toYamlString(v);
var v2 = loadYaml(s);
expect(v, v2);
});
});
}
| yamlicious/test/writer_test.dart/0 | {'file_path': 'yamlicious/test/writer_test.dart', 'repo_id': 'yamlicious', 'token_count': 218} |
import 'package:flutter_driver/driver_extension.dart';
import 'package:flutter_hello_world/counter.dart' as app;
void main() {
// This line enables the extension.
enableFlutterDriverExtension();
// Call the `main()` function of the app, or call `runApp` with
// any widget you are interested in testing.
app.main();
}
| Dart-Code/src/test/test_projects/flutter_hello_world/test_driver/app.dart/0 | {'file_path': 'Dart-Code/src/test/test_projects/flutter_hello_world/test_driver/app.dart', 'repo_id': 'Dart-Code', 'token_count': 102} |
import 'package:my_package/my_thing.dart';
main() {
printMyThing();
}
| Dart-Code/src/test/test_projects/hello_world/bin/local_package.dart/0 | {'file_path': 'Dart-Code/src/test/test_projects/hello_world/bin/local_package.dart', 'repo_id': 'Dart-Code', 'token_count': 30} |
// // This file gets uncommented by the test when running to avoid
// // the below code generating errors when working on Dart Code.abstract
//
// import 'class_a.dart';
// class ClassB {
// ClassB() {
// var classA = ClassA();
// classA.createNonExistentMethod();
// }
// }
| Dart-Code/src/test/test_projects/hello_world/lib/create_method/class_b.dart/0 | {'file_path': 'Dart-Code/src/test/test_projects/hello_world/lib/create_method/class_b.dart', 'repo_id': 'Dart-Code', 'token_count': 95} |
import 'package:first_desktop_application/main.dart' show MyAppState;
import 'package:flutter/material.dart' show GlobalKey;
class RootService {
final GlobalKey<MyAppState> rootKey = GlobalKey();
}
| Experiments_with_Desktop/first_desktop_application/lib/app-level/services/root_service.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/app-level/services/root_service.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 63} |
import 'dart:io';
import 'package:first_desktop_application/crypto/api/crypto.api.dart';
import 'base_cli_command.dart';
class CryptoCmd extends BaseCLICommand {
final cmdName = 'btc';
final desc = 'Shows the price of Bitcoin';
static CrptoAPI cryptoAPI = CrptoAPI();
@override
String get description => desc;
@override
String get name => cmdName;
@override
Future<void> run() async {
final data = await cryptoAPI.fetchData();
stdout.writeln('USD: ${data.bpi.usd.rateFloat}');
stdout.writeln('EUR: ${data.bpi.eur.rateFloat}');
stdout.writeln('POUND: ${data.bpi.gbp.rateFloat}');
stdout.writeln('');
stdout.writeln('Updated at: ${data.time.updated}');
stdout.writeln('Price by: ${data.disclaimer}');
stdout.writeln('');
}
}
| Experiments_with_Desktop/first_desktop_application/lib/crypto/commands/crypto.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/crypto/commands/crypto.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 299} |
import 'package:flutter/material.dart';
class FlightBarcode extends StatelessWidget {
const FlightBarcode({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 14.0),
child: Image.asset('assets/images/barcode.png'),
),
);
}
}
| Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/flight_barcode.dart/0 | {'file_path': 'Experiments_with_Desktop/first_desktop_application/lib/flipping/widgets/flight_barcode.dart', 'repo_id': 'Experiments_with_Desktop', 'token_count': 214} |
import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:xafe/app/authentication/domain/params/post_params/post_params.dart';
import 'package:xafe/app/authentication/domain/repository/authentication_repo.dart';
import 'package:xafe/core/error/failures.dart';
class LoginUser {
LoginUser(this._repository);
final AuthenticationRepo _repository;
Future<Either<Failure, User>> call(EmailPasswordParams params) async =>
await _repository.loginUser(params);
}
| Xafe/lib/app/authentication/domain/usecases/login_user.dart/0 | {'file_path': 'Xafe/lib/app/authentication/domain/usecases/login_user.dart', 'repo_id': 'Xafe', 'token_count': 173} |
import 'package:dartz/dartz.dart';
import 'package:xafe/app/budget/data/models/budget_model.dart';
import 'package:xafe/app/home/data/models/expense_model.dart';
import 'package:xafe/core/error/failures.dart';
abstract class BudgetRepo {
Stream<List<BudgetModel>> listenToBudgets();
Stream<List<ExpenseModel>> listenToBudgetExpenses(String budgetId);
Future<Either<Failure, void>> createBudget(BudgetModel params);
Future<Either<Failure, void>> createBudgetExpense(
ExpenseModel params,
String budgetId,
);
Future<Either<Failure, void>> deleteBudget(String budgetId);
Future<Either<Failure, void>> editBudget(BudgetModel params);
}
| Xafe/lib/app/budget/domain/repository/budget_repo.dart/0 | {'file_path': 'Xafe/lib/app/budget/domain/repository/budget_repo.dart', 'repo_id': 'Xafe', 'token_count': 219} |
import 'package:xafe/app/categories/data/datasource/categories_datasource.dart';
import 'package:xafe/app/categories/data/datasource/impl/categories_datasource_impl.dart';
import 'package:xafe/app/categories/data/repository/categories_repo_impl.dart';
import 'package:xafe/app/categories/domain/repository/categories_repo.dart';
import 'package:xafe/app/categories/domain/usecases/create_category.dart';
import 'package:xafe/app/categories/domain/usecases/listen_to_categories.dart';
import 'package:xafe/core/config/di_config.dart';
import 'domain/usecases/delete_category.dart';
void registerCategoriesDIs() {
//Use cases
locator.registerLazySingleton(() => CreateCategory(locator()));
locator.registerLazySingleton(() => ListenToCategories(locator()));
locator.registerLazySingleton(() => DeleteCategory(locator()));
//Repository
locator.registerLazySingleton<CategoriesRepo>(
() => CategoriesRepoImpl(
locator(),
),
);
// Data sources
locator.registerLazySingleton<CategoriesDataSource>(
() => CategoriesDataSourceImpl(
locator(),
),
);
}
| Xafe/lib/app/categories/categories_dependencies.dart/0 | {'file_path': 'Xafe/lib/app/categories/categories_dependencies.dart', 'repo_id': 'Xafe', 'token_count': 386} |
import 'package:dartz/dartz.dart';
import 'package:xafe/app/home/data/datasource/home_datasource.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';
import 'package:xafe/core/error/helpers/helpers.dart';
class HomeRepoImpl implements HomeRepo {
HomeRepoImpl(this._dataSource);
final HomeDataSource _dataSource;
@override
Future<Either<Failure, void>> addAnExpense(ExpenseModel params) {
return successFailureInterceptor(
() => _dataSource.addAnExpense(params),
);
}
@override
Stream<List<ExpenseModel>> listenToExpenses() {
return _dataSource.listenToExpenses();
}
}
| Xafe/lib/app/home/data/repository/home_repo_impl.dart/0 | {'file_path': 'Xafe/lib/app/home/data/repository/home_repo_impl.dart', 'repo_id': 'Xafe', 'token_count': 268} |
export 'src/hive_db.dart';
| Xafe/lib/core/config/local_storage/local_storage.dart/0 | {'file_path': 'Xafe/lib/core/config/local_storage/local_storage.dart', 'repo_id': 'Xafe', 'token_count': 13} |
import 'package:flutter/material.dart';
import 'package:xafe/src/res/values/styles/form_style.dart';
import '../res.dart';
ThemeData xafeTheme(BuildContext context) => ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
canvasColor: kColorWhite,
primarySwatch: const MaterialColor(
0xFF0F0627,
<int, Color>{
50: kColorAppBlack,
100: kColorAppBlack,
200: kColorAppBlack,
300: kColorAppBlack,
400: kColorAppBlack,
500: kColorAppBlack,
600: kColorAppBlack,
700: kColorAppBlack,
800: kColorAppBlack,
900: kColorAppBlack,
},
),
primaryColor: kColorAppBlack,
backgroundColor: kColorWhite,
scaffoldBackgroundColor: kColorWhite,
brightness: Brightness.light,
fontFamily: 'EuclidaCircular',
inputDecorationTheme: xafeFormTheme,
);
| Xafe/lib/src/res/themes/themes.dart/0 | {'file_path': 'Xafe/lib/src/res/themes/themes.dart', 'repo_id': 'Xafe', 'token_count': 417} |
import 'package:flutter/widgets.dart';
import 'package:xafe/src/utils/scaler/scaler.dart';
typedef ResponsiveBuilder = Widget Function(
BuildContext context,
Size size,
);
class ResponsiveSafeArea extends StatelessWidget {
const ResponsiveSafeArea({
Key key,
this.padding = 8.0,
@required ResponsiveBuilder builder,
}) : responsiveBuilder = builder,
super(key: key);
final ResponsiveBuilder responsiveBuilder;
final double padding;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: context.insetsAll(padding),
child: LayoutBuilder(
builder: (context, constraints) {
return responsiveBuilder(
context,
constraints.biggest,
);
},
),
),
);
}
}
class ResponsiveNoSafeArea extends StatelessWidget {
const ResponsiveNoSafeArea({
Key key,
this.padding = 8.0,
@required ResponsiveBuilder builder,
}) : responsiveBuilder = builder,
super(key: key);
final ResponsiveBuilder responsiveBuilder;
final double padding;
@override
Widget build(BuildContext context) {
return Padding(
padding: context.insetsAll(padding),
child: LayoutBuilder(
builder: (context, constraints) {
return responsiveBuilder(
context,
constraints.biggest,
);
},
),
);
}
}
| Xafe/lib/src/utils/scaler/src/screens.dart/0 | {'file_path': 'Xafe/lib/src/utils/scaler/src/screens.dart', 'repo_id': 'Xafe', 'token_count': 575} |
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:{{project_name.snakeCase()}}/profile/domain/user_repository.dart';
class RemoteUserRepository extends UserRepository {
@override
Future<AuthUser> getCurrentUser() async {
final user = await Amplify.Auth.getCurrentUser();
return user;
}
}
| amplify_starter/__brick__/{{project_name}}/lib/profile/domain/remote_user_repository.dart/0 | {'file_path': 'amplify_starter/__brick__/{{project_name}}/lib/profile/domain/remote_user_repository.dart', 'repo_id': 'amplify_starter', 'token_count': 110} |
import 'package:plugin/plugin.dart';
Future<void> main(List<String> args) async {
await startPlugin(
args: args,
pluginName: 'analyzer_plugin',
pluginInterfaceName: 'AnalyzerPlugin',
mainSource: r'''
import 'package:analyzer_plugin/analyzer_plugin.dart';
import 'package:mydartanalyzer/mydartanalyzer.dart';
Future<void> main(
List<String> args,
List<AnalyzerPlugin> plugins
) {
return start(args, plugins);
}
''',
);
}
| analyzer_plugins/packages/mydartanalyzer/bin/main.dart/0 | {'file_path': 'analyzer_plugins/packages/mydartanalyzer/bin/main.dart', 'repo_id': 'analyzer_plugins', 'token_count': 165} |
import 'package:sample/sample.dart';
import 'package:test/test.dart';
void main() {
test('calculate', () {
expect(calculate(), 42);
});
}
| article-hub/dart/sample/test/sample_test.dart/0 | {'file_path': 'article-hub/dart/sample/test/sample_test.dart', 'repo_id': 'article-hub', 'token_count': 57} |
import 'package:audioplayers/audioplayers.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_audio/bgm.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:sample/game/cubit/cubit.dart';
class _MockAudioCache extends Mock implements AudioCache {}
class _MockAudioPlayer extends Mock implements AudioPlayer {}
class _MockBgm extends Mock implements Bgm {}
void main() {
group('AudioCubit', () {
TestWidgetsFlutterBinding.ensureInitialized();
late AudioCache audioCache;
late AudioPlayer effectPlayer;
late Bgm bgm;
late AudioPlayer bgmPlayer;
setUp(() {
audioCache = _MockAudioCache();
effectPlayer = _MockAudioPlayer();
bgm = _MockBgm();
bgmPlayer = _MockAudioPlayer();
when(() => bgm.audioPlayer).thenReturn(bgmPlayer);
when(effectPlayer.dispose).thenAnswer((_) => Future.value());
when(bgmPlayer.dispose).thenAnswer((_) => Future.value());
});
test('can be instantiated', () {
expect(AudioCubit(audioCache: audioCache), isA<AudioCubit>());
});
blocTest<AudioCubit, AudioState>(
'toggleVolume mutes the volume when the volume is not 0',
setUp: () {
when(() => effectPlayer.setVolume(any())).thenAnswer((_) async {});
when(() => bgmPlayer.setVolume(any())).thenAnswer((_) async {});
},
build: () => AudioCubit.test(effectPlayer: effectPlayer, bgm: bgm),
act: (cubit) => cubit.toggleVolume(),
expect: () => [const AudioState(volume: 0)],
verify: (_) {
verify(() => effectPlayer.setVolume(any(that: equals(0)))).called(1);
verify(() => bgmPlayer.setVolume(any(that: equals(0)))).called(1);
},
);
blocTest<AudioCubit, AudioState>(
'toggleVolume unmutes the volume when the volume is 0',
setUp: () {
when(() => effectPlayer.setVolume(any())).thenAnswer((_) async {});
when(() => bgmPlayer.setVolume(any())).thenAnswer((_) async {});
},
build: () {
return AudioCubit.test(effectPlayer: effectPlayer, bgm: bgm, volume: 0);
},
act: (cubit) => cubit.toggleVolume(),
expect: () => [const AudioState()],
verify: (_) {
verify(() => effectPlayer.setVolume(any(that: equals(1)))).called(1);
verify(() => bgmPlayer.setVolume(any(that: equals(1)))).called(1);
},
);
});
}
| article-hub/flame-game/sample/test/game/cubit/audio_cubit_test.dart/0 | {'file_path': 'article-hub/flame-game/sample/test/game/cubit/audio_cubit_test.dart', 'repo_id': 'article-hub', 'token_count': 962} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'delegate/stream.dart';
import 'stream_completer.dart';
import 'utils.dart';
/// A [Stream] wrapper that forwards to another [Stream] that's initialized
/// lazily.
///
/// This class allows a concrete `Stream` to be created only once it has a
/// listener. It's useful to wrapping APIs that do expensive computation to
/// produce a `Stream`.
class LazyStream<T> extends Stream<T> {
/// The callback that's called to create the inner stream.
FutureOrCallback<Stream<T>> _callback;
/// Creates a single-subscription `Stream` that calls [callback] when it gets
/// a listener and forwards to the returned stream.
LazyStream(FutureOr<Stream<T>> Function() callback) : _callback = callback {
// Explicitly check for null because we null out [_callback] internally.
if (_callback == null) throw ArgumentError.notNull('callback');
}
@override
StreamSubscription<T> listen(void Function(T) onData,
{Function onError, void Function() onDone, bool cancelOnError}) {
if (_callback == null) {
throw StateError('Stream has already been listened to.');
}
// Null out the callback before we invoke it to ensure that even while
// running it, this can't be called twice.
var callback = _callback;
_callback = null;
var result = callback();
Stream<T> stream;
if (result is Future<Stream<T>>) {
stream = StreamCompleter.fromFuture(result.then((stream) {
return DelegatingStream.typed<T>(stream);
}));
} else {
stream = DelegatingStream.typed<T>(result as Stream);
}
return stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
}
| async/lib/src/lazy_stream.dart/0 | {'file_path': 'async/lib/src/lazy_stream.dart', 'repo_id': 'async', 'token_count': 600} |
// 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/handler_transformer.dart';
import 'stream_sink_transformer/stream_transformer_wrapper.dart';
import 'stream_sink_transformer/typed.dart';
/// A [StreamSinkTransformer] transforms the events being passed to a sink.
///
/// This works on the same principle as a [StreamTransformer]. Each transformer
/// defines a [bind] method that takes in the original [StreamSink] and returns
/// the transformed version. However, where a [StreamTransformer] transforms
/// events after they leave the stream, this transforms them before they enter
/// the sink.
///
/// Transformers must be able to have `bind` called used multiple times.
abstract class StreamSinkTransformer<S, T> {
/// Creates a [StreamSinkTransformer] that transforms events and errors
/// using [transformer].
///
/// This is equivalent to piping all events from the outer sink through a
/// stream transformed by [transformer] and from there into the inner sink.
const factory StreamSinkTransformer.fromStreamTransformer(
StreamTransformer<S, T> transformer) = StreamTransformerWrapper<S, T>;
/// Creates a [StreamSinkTransformer] that delegates events to the given
/// handlers.
///
/// The handlers work exactly as they do for [StreamTransformer.fromHandlers].
/// They're called for each incoming event, and any actions on the sink
/// they're passed are forwarded to the inner sink. If a handler is omitted,
/// the event is passed through unaltered.
factory StreamSinkTransformer.fromHandlers(
{void Function(S, EventSink<T>) handleData,
void Function(Object, StackTrace, EventSink<T>) handleError,
void Function(EventSink<T>) handleDone}) {
return HandlerTransformer<S, T>(handleData, handleError, handleDone);
}
/// Transforms the events passed to [sink].
///
/// Creates a new sink. When events are passed to the returned sink, it will
/// transform them and pass the transformed versions to [sink].
StreamSink<S> bind(StreamSink<T> sink);
/// Creates a wrapper that coerces the type of [transformer].
///
/// This soundly converts a [StreamSinkTransformer] to a
/// `StreamSinkTransformer<S, T>`, regardless of its original generic type.
/// This means that calls to [StreamSink.add] on the returned sink may throw a
/// [CastError] if the argument type doesn't match the reified type of the
/// sink.
static StreamSinkTransformer<S, T> typed<S, T>(
StreamSinkTransformer transformer) =>
transformer is StreamSinkTransformer<S, T>
? transformer
: TypeSafeStreamSinkTransformer(transformer);
}
| async/lib/src/stream_sink_transformer.dart/0 | {'file_path': 'async/lib/src/stream_sink_transformer.dart', 'repo_id': 'async', 'token_count': 820} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:async/src/future_group.dart';
import 'package:test/test.dart';
import 'utils.dart';
void main() {
FutureGroup futureGroup;
setUp(() {
futureGroup = FutureGroup();
});
group('with no futures', () {
test('never completes if nothing happens', () async {
var completed = false;
futureGroup.future.then((_) => completed = true);
await flushMicrotasks();
expect(completed, isFalse);
});
test("completes once it's closed", () {
expect(futureGroup.future, completion(isEmpty));
futureGroup.close();
});
});
group('with a future that already completed', () {
test('never completes if nothing happens', () async {
futureGroup.add(Future.value());
await flushMicrotasks();
var completed = false;
futureGroup.future.then((_) => completed = true);
await flushMicrotasks();
expect(completed, isFalse);
});
test("completes once it's closed", () async {
futureGroup.add(Future.value());
await flushMicrotasks();
expect(futureGroup.future, completes);
futureGroup.close();
});
test("completes to that future's value", () {
futureGroup.add(Future.value(1));
futureGroup.close();
expect(futureGroup.future, completion(equals([1])));
});
test("completes to that future's error, even if it's not closed", () {
futureGroup.add(Future.error('error'));
expect(futureGroup.future, throwsA('error'));
});
});
test('completes once all contained futures complete', () async {
var completer1 = Completer();
var completer2 = Completer();
var completer3 = Completer();
futureGroup.add(completer1.future);
futureGroup.add(completer2.future);
futureGroup.add(completer3.future);
futureGroup.close();
var completed = false;
futureGroup.future.then((_) => completed = true);
completer1.complete();
await flushMicrotasks();
expect(completed, isFalse);
completer2.complete();
await flushMicrotasks();
expect(completed, isFalse);
completer3.complete();
await flushMicrotasks();
expect(completed, isTrue);
});
test('completes to the values of the futures in order of addition', () {
var completer1 = Completer();
var completer2 = Completer();
var completer3 = Completer();
futureGroup.add(completer1.future);
futureGroup.add(completer2.future);
futureGroup.add(completer3.future);
futureGroup.close();
// Complete the completers in reverse order to prove that that doesn't
// affect the result order.
completer3.complete(3);
completer2.complete(2);
completer1.complete(1);
expect(futureGroup.future, completion(equals([1, 2, 3])));
});
test("completes to the first error to be emitted, even if it's not closed",
() {
var completer1 = Completer();
var completer2 = Completer();
var completer3 = Completer();
futureGroup.add(completer1.future);
futureGroup.add(completer2.future);
futureGroup.add(completer3.future);
completer2.completeError('error 2');
completer1.completeError('error 1');
expect(futureGroup.future, throwsA('error 2'));
});
group('onIdle:', () {
test('emits an event when the last pending future completes', () async {
var idle = false;
futureGroup.onIdle.listen((_) => idle = true);
var completer1 = Completer();
var completer2 = Completer();
var completer3 = Completer();
futureGroup.add(completer1.future);
futureGroup.add(completer2.future);
futureGroup.add(completer3.future);
await flushMicrotasks();
expect(idle, isFalse);
expect(futureGroup.isIdle, isFalse);
completer1.complete();
await flushMicrotasks();
expect(idle, isFalse);
expect(futureGroup.isIdle, isFalse);
completer2.complete();
await flushMicrotasks();
expect(idle, isFalse);
expect(futureGroup.isIdle, isFalse);
completer3.complete();
await flushMicrotasks();
expect(idle, isTrue);
expect(futureGroup.isIdle, isTrue);
});
test('emits an event each time it becomes idle', () async {
var idle = false;
futureGroup.onIdle.listen((_) => idle = true);
var completer = Completer();
futureGroup.add(completer.future);
completer.complete();
await flushMicrotasks();
expect(idle, isTrue);
expect(futureGroup.isIdle, isTrue);
idle = false;
completer = Completer();
futureGroup.add(completer.future);
await flushMicrotasks();
expect(idle, isFalse);
expect(futureGroup.isIdle, isFalse);
completer.complete();
await flushMicrotasks();
expect(idle, isTrue);
expect(futureGroup.isIdle, isTrue);
});
test('emits an event when the group closes', () async {
// It's important that the order of events here stays consistent over
// time, since code may rely on it in subtle ways.
var idle = false;
var onIdleDone = false;
var futureFired = false;
futureGroup.onIdle.listen(expectAsync1((_) {
expect(futureFired, isFalse);
idle = true;
}), onDone: expectAsync0(() {
expect(idle, isTrue);
expect(futureFired, isFalse);
onIdleDone = true;
}));
futureGroup.future.then(expectAsync1((_) {
expect(idle, isTrue);
expect(onIdleDone, isTrue);
futureFired = true;
}));
var completer = Completer();
futureGroup.add(completer.future);
futureGroup.close();
await flushMicrotasks();
expect(idle, isFalse);
expect(futureGroup.isIdle, isFalse);
completer.complete();
await flushMicrotasks();
expect(idle, isTrue);
expect(futureGroup.isIdle, isTrue);
expect(futureFired, isTrue);
});
});
}
| async/test/future_group_test.dart/0 | {'file_path': 'async/test/future_group_test.dart', 'repo_id': 'async', 'token_count': 2348} |
// Copyright (c) 2013, 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:test/test.dart';
// Test that stream listener callbacks all happen in the zone where the
// listen occurred.
void main() {
StreamController controller;
controller = StreamController();
testStream('singlesub-async', controller, controller.stream);
controller = StreamController.broadcast();
testStream('broadcast-async', controller, controller.stream);
controller = StreamController();
testStream(
'asbroadcast-async', controller, controller.stream.asBroadcastStream());
controller = StreamController(sync: true);
testStream('singlesub-sync', controller, controller.stream);
controller = StreamController.broadcast(sync: true);
testStream('broadcast-sync', controller, controller.stream);
controller = StreamController(sync: true);
testStream(
'asbroadcast-sync', controller, controller.stream.asBroadcastStream());
}
void testStream(String name, StreamController controller, Stream stream) {
test(name, () {
var outer = Zone.current;
runZoned(() {
var newZone1 = Zone.current;
StreamSubscription sub;
sub = stream.listen(expectAsync1((v) {
expect(v, 42);
expect(Zone.current, newZone1);
outer.run(() {
sub.onData(expectAsync1((v) {
expect(v, 37);
expect(Zone.current, newZone1);
runZoned(() {
sub.onData(expectAsync1((v) {
expect(v, 87);
expect(Zone.current, newZone1);
}));
});
if (controller is SynchronousStreamController) {
scheduleMicrotask(() => controller.add(87));
} else {
controller.add(87);
}
}));
});
if (controller is SynchronousStreamController) {
scheduleMicrotask(() => controller.add(37));
} else {
controller.add(37);
}
}));
});
controller.add(42);
});
}
| async/test/stream_zip_zone_test.dart/0 | {'file_path': 'async/test/stream_zip_zone_test.dart', 'repo_id': 'async', 'token_count': 847} |
import 'dart:async';
import 'package:atlas/atlas.dart';
/// `AtlasController` allows developers to manipulate `Atlas` after the map has been initialized.
abstract class AtlasController {
/// Moves the camera to the specified `CameraPosition`
Future<void> moveCamera(CameraPosition cameraPosition);
/// Updates the camera bounds based on the provided `LatLngBounds`
/// and adds padding around the bounds based on the provided `padding`.
Future<void> updateBounds(LatLngBounds bounds, double padding);
/// Return a [ScreenCoordinate] corresponding to the [LatLng] in the map view.
Future<LatLng> getLatLng(ScreenCoordinates screenCoordinates);
/// Returns a [LatLng] corresponding to the [ScreenCoordinate] in the map view.
Future<ScreenCoordinates> getScreenCoordinate(LatLng latLng);
}
| atlas/packages/atlas/lib/src/atlas_controller.dart/0 | {'file_path': 'atlas/packages/atlas/lib/src/atlas_controller.dart', 'repo_id': 'atlas', 'token_count': 226} |
import 'package:atlas/atlas.dart';
import 'package:flutter_test/flutter_test.dart';
main() {
group('CameraPosition', () {
test('should throw AssertionError if target is null', () {
try {
CameraPosition(target: null);
fail('should throw AssertionError');
} catch (error) {
expect(error, isAssertionError);
}
});
});
}
| atlas/packages/atlas/test/camera_position_test.dart/0 | {'file_path': 'atlas/packages/atlas/test/camera_position_test.dart', 'repo_id': 'atlas', 'token_count': 152} |
name: example
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.2.2 <3.0.0"
dependencies:
flutter:
sdk: flutter
google_atlas:
path: ../
flutter:
uses-material-design: true
assets:
- assets/
| atlas/packages/google_atlas/example/pubspec.yaml/0 | {'file_path': 'atlas/packages/google_atlas/example/pubspec.yaml', 'repo_id': 'atlas', 'token_count': 109} |
name: pull-request
on:
pull_request:
types:
- opened
- reopened
- synchronize
- ready_for_review
jobs:
call-test:
uses: ./.github/workflows/test.yml
with:
enable_android: ${{ github.event.pull_request.draft == false }}
enable_web: ${{ github.event.pull_request.draft == false }}
enable_ios: ${{ github.event.pull_request.draft == false }}
enable_windows: ${{ github.event.pull_request.draft == false }}
enable_linux: ${{ github.event.pull_request.draft == false }}
enable_macos: ${{ github.event.pull_request.draft == false }}
| audioplayers/.github/workflows/pull-request.yml/0 | {'file_path': 'audioplayers/.github/workflows/pull-request.yml', 'repo_id': 'audioplayers', 'token_count': 236} |
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../test_utils.dart';
import '../app_test_utils.dart';
extension PropertiesWidgetTester on WidgetTester {
Future<void> testDuration(
Duration? duration, {
Duration timeout = const Duration(seconds: 4),
}) async {
printWithTimeOnFailure('Test Duration: $duration');
final st = StackTrace.current.toString();
await waitFor(
() async {
await scrollToAndTap(const Key('refreshButton'));
await pump();
expectWidgetHasDuration(
const Key('durationText'),
// TODO(gustl22): once duration is always null for streams,
// then can remove fallback for Duration.zero
matcher: (Duration? actual) => durationRangeMatcher(
actual ?? Duration.zero,
duration ?? Duration.zero,
),
);
},
timeout: timeout,
stackTrace: st,
);
}
Future<void> testPosition(
Duration? position, {
Matcher Function(Duration?) matcher = equals,
Duration timeout = const Duration(seconds: 4),
}) async {
printWithTimeOnFailure('Test Position: $position');
final st = StackTrace.current.toString();
await waitFor(
() async {
await scrollToAndTap(const Key('refreshButton'));
await pump();
expectWidgetHasDuration(
const Key('positionText'),
matcher: matcher(position),
);
},
timeout: timeout,
stackTrace: st,
);
}
Future<void> testPlayerState(
PlayerState playerState, {
Duration timeout = const Duration(seconds: 4),
}) async {
printWithTimeOnFailure('Test PlayerState: $playerState');
final st = StackTrace.current.toString();
await waitFor(
() async {
await scrollToAndTap(const Key('refreshButton'));
await pump();
expectWidgetHasText(
const Key('playerStateText'),
matcher: contains(playerState.toString()),
);
},
timeout: timeout,
stackTrace: st,
);
}
}
| audioplayers/packages/audioplayers/example/integration_test/app/tabs/properties.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/example/integration_test/app/tabs/properties.dart', 'repo_id': 'audioplayers', 'token_count': 852} |
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
// This code is also used in the example.md. Please keep it up to date.
class PlayerWidget extends StatefulWidget {
final AudioPlayer player;
const PlayerWidget({
required this.player,
super.key,
});
@override
State<StatefulWidget> createState() {
return _PlayerWidgetState();
}
}
class _PlayerWidgetState extends State<PlayerWidget> {
PlayerState? _playerState;
Duration? _duration;
Duration? _position;
StreamSubscription? _durationSubscription;
StreamSubscription? _positionSubscription;
StreamSubscription? _playerCompleteSubscription;
StreamSubscription? _playerStateChangeSubscription;
bool get _isPlaying => _playerState == PlayerState.playing;
bool get _isPaused => _playerState == PlayerState.paused;
String get _durationText => _duration?.toString().split('.').first ?? '';
String get _positionText => _position?.toString().split('.').first ?? '';
AudioPlayer get player => widget.player;
@override
void initState() {
super.initState();
// Use initial values from player
_playerState = player.state;
player.getDuration().then(
(value) => setState(() {
_duration = value;
}),
);
player.getCurrentPosition().then(
(value) => setState(() {
_position = value;
}),
);
_initStreams();
}
@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
void dispose() {
_durationSubscription?.cancel();
_positionSubscription?.cancel();
_playerCompleteSubscription?.cancel();
_playerStateChangeSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final color = Theme.of(context).primaryColor;
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
key: const Key('play_button'),
onPressed: _isPlaying ? null : _play,
iconSize: 48.0,
icon: const Icon(Icons.play_arrow),
color: color,
),
IconButton(
key: const Key('pause_button'),
onPressed: _isPlaying ? _pause : null,
iconSize: 48.0,
icon: const Icon(Icons.pause),
color: color,
),
IconButton(
key: const Key('stop_button'),
onPressed: _isPlaying || _isPaused ? _stop : null,
iconSize: 48.0,
icon: const Icon(Icons.stop),
color: color,
),
],
),
Slider(
onChanged: (value) {
final duration = _duration;
if (duration == null) {
return;
}
final position = value * duration.inMilliseconds;
player.seek(Duration(milliseconds: position.round()));
},
value: (_position != null &&
_duration != null &&
_position!.inMilliseconds > 0 &&
_position!.inMilliseconds < _duration!.inMilliseconds)
? _position!.inMilliseconds / _duration!.inMilliseconds
: 0.0,
),
Text(
_position != null
? '$_positionText / $_durationText'
: _duration != null
? _durationText
: '',
style: const TextStyle(fontSize: 16.0),
),
],
);
}
void _initStreams() {
_durationSubscription = player.onDurationChanged.listen((duration) {
setState(() => _duration = duration);
});
_positionSubscription = player.onPositionChanged.listen(
(p) => setState(() => _position = p),
);
_playerCompleteSubscription = player.onPlayerComplete.listen((event) {
setState(() {
_playerState = PlayerState.stopped;
_position = Duration.zero;
});
});
_playerStateChangeSubscription =
player.onPlayerStateChanged.listen((state) {
setState(() {
_playerState = state;
});
});
}
Future<void> _play() async {
await player.resume();
setState(() => _playerState = PlayerState.playing);
}
Future<void> _pause() async {
await player.pause();
setState(() => _playerState = PlayerState.paused);
}
Future<void> _stop() async {
await player.stop();
setState(() {
_playerState = PlayerState.stopped;
_position = Duration.zero;
});
}
}
| audioplayers/packages/audioplayers/example/lib/components/player_widget.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/example/lib/components/player_widget.dart', 'repo_id': 'audioplayers', 'token_count': 2094} |
extension UriCoder on Uri {
static String encodeOnce(String uri) {
try {
// If decoded differs, the uri was already encoded.
final decodedUri = Uri.decodeFull(uri);
if (decodedUri != uri) {
return uri;
}
} on ArgumentError catch (_) {}
return Uri.encodeFull(uri);
}
}
| audioplayers/packages/audioplayers/lib/src/uri_ext.dart/0 | {'file_path': 'audioplayers/packages/audioplayers/lib/src/uri_ext.dart', 'repo_id': 'audioplayers', 'token_count': 132} |
include: package:flame_lint/analysis_options.yaml
| audioplayers/packages/audioplayers_platform_interface/analysis_options.yaml/0 | {'file_path': 'audioplayers/packages/audioplayers_platform_interface/analysis_options.yaml', 'repo_id': 'audioplayers', 'token_count': 16} |
//ignore_for_file: avoid_redundant_argument_values
import 'package:audioplayers_platform_interface/audioplayers_platform_interface.dart';
import 'package:audioplayers_platform_interface/src/api/audio_context_config.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('Create default AudioContext', () async {
final context = AudioContext();
expect(
context,
AudioContext(
android: const AudioContextAndroid(
isSpeakerphoneOn: false,
audioMode: AndroidAudioMode.normal,
stayAwake: false,
contentType: AndroidContentType.music,
usageType: AndroidUsageType.media,
audioFocus: AndroidAudioFocus.gain,
),
iOS: AudioContextIOS(
category: AVAudioSessionCategory.playback,
options: const {},
),
),
);
});
test('Check AudioContextConfig assertions', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
const boolValues = {true, false};
const focusValues = AudioContextConfigFocus.values;
const routeValues = AudioContextConfigRoute.values;
final throwsAssertion = [];
for (final focus in focusValues) {
for (final isRespectSilence in boolValues) {
for (final isStayAwake in boolValues) {
for (final route in routeValues) {
final config = AudioContextConfig(
focus: focus,
respectSilence: isRespectSilence,
stayAwake: isStayAwake,
route: route,
);
try {
config.build();
throwsAssertion.add(false);
} on AssertionError catch (e) {
if (e.message
.toString()
.startsWith('Invalid AudioContextConfig')) {
throwsAssertion.add(true);
} else {
fail(
'Assertion of $config does not match the expected '
'description. See: $e',
);
}
}
}
}
}
}
// Ensure assertions keep thrown on the correct cases.
expect(
throwsAssertion,
const [
false,
false,
true,
false,
false,
true,
false,
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
true,
false,
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
true,
false,
false,
false,
false,
false,
false,
],
);
});
test('Create invalid AudioContextIOS', () async {
try {
// Throws AssertionError:
AudioContextIOS(
category: AVAudioSessionCategory.ambient,
options: const {AVAudioSessionOptions.mixWithOthers},
);
fail('AssertionError not thrown');
// ignore: avoid_catches_without_on_clauses
} catch (e) {
expect(e, isInstanceOf<AssertionError>());
expect(
(e as AssertionError).message,
'You can set the option `mixWithOthers` explicitly only if the audio '
'session category is `playAndRecord`, `playback`, or `multiRoute`.');
}
});
test('Equality of AudioContextIOS', () async {
final context1 = AudioContextIOS(
category: AVAudioSessionCategory.playAndRecord,
options: const {
AVAudioSessionOptions.mixWithOthers,
AVAudioSessionOptions.defaultToSpeaker,
},
);
final context2 = AudioContextIOS(
category: AVAudioSessionCategory.playAndRecord,
options: const {
AVAudioSessionOptions.defaultToSpeaker,
AVAudioSessionOptions.mixWithOthers,
},
);
expect(context1, context2);
});
}
| audioplayers/packages/audioplayers_platform_interface/test/audio_context_test.dart/0 | {'file_path': 'audioplayers/packages/audioplayers_platform_interface/test/audio_context_test.dart', 'repo_id': 'audioplayers', 'token_count': 1873} |
name: Run awesome lint
on:
push:
# Run against main branch only.
branches: [main]
pull_request:
# Include events emitted on code change only.
types: [opened, synchronize]
jobs:
awesome-lint-workflow:
runs-on: ubuntu-latest
name: Linting with awesome-lint
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js 10.x
uses: actions/setup-node@v4
with:
node-version: 18.x
- run: npx awesome-lint
| awesome-flame/.github/workflows/lint.yml/0 | {'file_path': 'awesome-flame/.github/workflows/lint.yml', 'repo_id': 'awesome-flame', 'token_count': 242} |
import 'dart:ui';
import 'package:flame/components/component.dart';
import 'package:flame/sprite.dart';
import '../constants.dart';
class Floor extends SpriteComponent {
Floor() : super.fromSprite(1.0, BAR_SIZE, Sprite('base_bottom.png'));
@override
bool isHud() {
return true;
}
@override
void resize(Size size) {
x = 0.0;
y = sizeBottom(size);
width = size.width;
}
}
| bgug/lib/components/floor.dart/0 | {'file_path': 'bgug/lib/components/floor.dart', 'repo_id': 'bgug', 'token_count': 157} |
import 'dart:ui';
import 'package:flame/palette.dart';
class Palette {
static const PaletteEntry white = BasicPalette.white;
// toast
static const PaletteEntry bg = const PaletteEntry(Color(0xFFAC3232));
static const PaletteEntry text = const PaletteEntry(Color(0xFFDA9A00));
// block
static const PaletteEntry grey = const PaletteEntry(Color(0xFF404040));
static const PaletteEntry green = const PaletteEntry(Color(0xFF54a286));
}
| bgug/lib/palette.dart/0 | {'file_path': 'bgug/lib/palette.dart', 'repo_id': 'bgug', 'token_count': 147} |
library bitmap;
export 'src/bitmap.dart';
export 'src/ffi.dart';
export 'src/operation/operation.dart';
| bitmap/lib/bitmap.dart/0 | {'file_path': 'bitmap/lib/bitmap.dart', 'repo_id': 'bitmap', 'token_count': 40} |
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Figure out a way to test this with FFI', () {});
}
| bitmap/test/bitmap_test.dart/0 | {'file_path': 'bitmap/test/bitmap_test.dart', 'repo_id': 'bitmap', 'token_count': 44} |
name: angular_counter
description: A web app that uses angular_bloc
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
angular_bloc: ^8.0.0
bloc: ^8.1.1
ngdart: ^8.0.0-dev.0
dev_dependencies:
build_runner: ^2.0.0
build_web_compilers: ^3.0.0
| bloc/examples/angular_counter/pubspec.yaml/0 | {'file_path': 'bloc/examples/angular_counter/pubspec.yaml', 'repo_id': 'bloc', 'token_count': 120} |
export 'item.dart';
| bloc/examples/flutter_complex_list/lib/complex_list/models/models.dart/0 | {'file_path': 'bloc/examples/flutter_complex_list/lib/complex_list/models/models.dart', 'repo_id': 'bloc', 'token_count': 8} |
include: package:very_good_analysis/analysis_options.3.1.0.yaml
| bloc/examples/flutter_counter/analysis_options.yaml/0 | {'file_path': 'bloc/examples/flutter_counter/analysis_options.yaml', 'repo_id': 'bloc', 'token_count': 23} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_counter/counter/counter.dart';
/// {@template counter_view}
/// A [StatelessWidget] which reacts to the provided
/// [CounterCubit] state and notifies it in response to user input.
/// {@endtemplate}
class CounterView extends StatelessWidget {
/// {@macro counter_view}
const CounterView({super.key});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('$state', style: textTheme.displayMedium);
},
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
key: const Key('counterView_increment_floatingActionButton'),
child: const Icon(Icons.add),
onPressed: () => context.read<CounterCubit>().increment(),
),
const SizedBox(height: 8),
FloatingActionButton(
key: const Key('counterView_decrement_floatingActionButton'),
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterCubit>().decrement(),
),
],
),
);
}
}
| bloc/examples/flutter_counter/lib/counter/view/counter_view.dart/0 | {'file_path': 'bloc/examples/flutter_counter/lib/counter/view/counter_view.dart', 'repo_id': 'bloc', 'token_count': 617} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_dynamic_form/new_car/new_car.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('NewCarEvent', () {
group('NewCarFormLoaded', () {
test('supports value comparison', () {
expect(NewCarFormLoaded(), NewCarFormLoaded());
});
});
group('NewCarBrandChanged', () {
const mockCarBrand = 'Chevy';
test('supports value comparison', () {
expect(NewCarBrandChanged(), NewCarBrandChanged());
expect(
NewCarBrandChanged(brand: mockCarBrand),
NewCarBrandChanged(brand: mockCarBrand),
);
});
});
group('NewCarModelChanged', () {
const mockCarModel = 'Malibu';
test('supports value comparison', () {
expect(NewCarModelChanged(), NewCarModelChanged());
expect(
NewCarModelChanged(model: mockCarModel),
NewCarModelChanged(model: mockCarModel),
);
});
});
group('NewCarYearChanged', () {
const mockYear = '2021';
test('supports value comparison', () {
expect(NewCarYearChanged(), NewCarYearChanged());
expect(
NewCarYearChanged(year: mockYear),
NewCarYearChanged(year: mockYear),
);
});
});
});
}
| bloc/examples/flutter_dynamic_form/test/new_car/bloc/new_car_event_test.dart/0 | {'file_path': 'bloc/examples/flutter_dynamic_form/test/new_car/bloc/new_car_event_test.dart', 'repo_id': 'bloc', 'token_count': 545} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_firebase_login/app/app.dart';
import 'package:flutter_firebase_login/home/home.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
static Page<void> page() => const MaterialPage<void>(child: HomePage());
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
final user = context.select((AppBloc bloc) => bloc.state.user);
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
actions: <Widget>[
IconButton(
key: const Key('homePage_logout_iconButton'),
icon: const Icon(Icons.exit_to_app),
onPressed: () {
context.read<AppBloc>().add(const AppLogoutRequested());
},
)
],
),
body: Align(
alignment: const Alignment(0, -1 / 3),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Avatar(photo: user.photo),
const SizedBox(height: 4),
Text(user.email ?? '', style: textTheme.titleLarge),
const SizedBox(height: 4),
Text(user.name ?? '', style: textTheme.headlineSmall),
],
),
),
);
}
}
| bloc/examples/flutter_firebase_login/lib/home/view/home_page.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/lib/home/view/home_page.dart', 'repo_id': 'bloc', 'token_count': 611} |
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
final theme = ThemeData(
textTheme: GoogleFonts.openSansTextTheme(),
primaryColorDark: const Color(0xFF0097A7),
primaryColorLight: const Color(0xFFB2EBF2),
primaryColor: const Color(0xFF00BCD4),
colorScheme: const ColorScheme.light(secondary: Color(0xFF009688)),
scaffoldBackgroundColor: const Color(0xFFE0F2F1),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
);
| bloc/examples/flutter_firebase_login/lib/theme.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/lib/theme.dart', 'repo_id': 'bloc', 'token_count': 200} |
import 'package:formz/formz.dart';
/// Validation errors for the [Email] [FormzInput].
enum EmailValidationError {
/// Generic invalid error.
invalid
}
/// {@template email}
/// Form input for an email input.
/// {@endtemplate}
class Email extends FormzInput<String, EmailValidationError> {
/// {@macro email}
const Email.pure() : super.pure('');
/// {@macro email}
const Email.dirty([super.value = '']) : super.dirty();
static final RegExp _emailRegExp = RegExp(
r'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$',
);
@override
EmailValidationError? validator(String? value) {
return _emailRegExp.hasMatch(value ?? '')
? null
: EmailValidationError.invalid;
}
}
| bloc/examples/flutter_firebase_login/packages/form_inputs/lib/src/email.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/packages/form_inputs/lib/src/email.dart', 'repo_id': 'bloc', 'token_count': 294} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_firebase_login/sign_up/sign_up.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:form_inputs/form_inputs.dart';
import 'package:formz/formz.dart';
void main() {
const email = Email.dirty('email');
const passwordString = 'password';
const password = Password.dirty(passwordString);
const confirmedPassword = ConfirmedPassword.dirty(
password: passwordString,
value: passwordString,
);
group('SignUpState', () {
test('supports value comparisons', () {
expect(SignUpState(), SignUpState());
});
test('returns same object when no properties are passed', () {
expect(SignUpState().copyWith(), SignUpState());
});
test('returns object with updated status when status is passed', () {
expect(
SignUpState().copyWith(status: FormzStatus.pure),
SignUpState(),
);
});
test('returns object with updated email when email is passed', () {
expect(
SignUpState().copyWith(email: email),
SignUpState(email: email),
);
});
test('returns object with updated password when password is passed', () {
expect(
SignUpState().copyWith(password: password),
SignUpState(password: password),
);
});
test(
'returns object with updated confirmedPassword'
' when confirmedPassword is passed', () {
expect(
SignUpState().copyWith(confirmedPassword: confirmedPassword),
SignUpState(confirmedPassword: confirmedPassword),
);
});
});
}
| bloc/examples/flutter_firebase_login/test/sign_up/cubit/sign_up_state_test.dart/0 | {'file_path': 'bloc/examples/flutter_firebase_login/test/sign_up/cubit/sign_up_state_test.dart', 'repo_id': 'bloc', 'token_count': 571} |
import 'package:formz/formz.dart';
enum PasswordValidationError { invalid }
class Password extends FormzInput<String, PasswordValidationError> {
const Password.pure([super.value = '']) : super.pure();
const Password.dirty([super.value = '']) : super.dirty();
static final _passwordRegex =
RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$');
@override
PasswordValidationError? validator(String? value) {
return _passwordRegex.hasMatch(value ?? '')
? null
: PasswordValidationError.invalid;
}
}
| bloc/examples/flutter_form_validation/lib/models/password.dart/0 | {'file_path': 'bloc/examples/flutter_form_validation/lib/models/password.dart', 'repo_id': 'bloc', 'token_count': 201} |
import 'package:flutter_graphql_jobs/api/api.dart';
import 'package:flutter_graphql_jobs/api/queries/queries.dart' as queries;
import 'package:graphql/client.dart';
class GetJobsRequestFailure implements Exception {}
class JobsApiClient {
const JobsApiClient({required GraphQLClient graphQLClient})
: _graphQLClient = graphQLClient;
factory JobsApiClient.create() {
final httpLink = HttpLink('https://api.graphql.jobs');
final link = Link.from([httpLink]);
return JobsApiClient(
graphQLClient: GraphQLClient(cache: GraphQLCache(), link: link),
);
}
final GraphQLClient _graphQLClient;
Future<List<Job>> getJobs() async {
final result = await _graphQLClient.query(
QueryOptions(document: gql(queries.getJobs)),
);
if (result.hasException) throw GetJobsRequestFailure();
final data = result.data?['jobs'] as List;
return data
.map((dynamic e) => Job.fromJson(e as Map<String, dynamic>))
.toList();
}
}
| bloc/examples/flutter_graphql_jobs/lib/api/job_api_client.dart/0 | {'file_path': 'bloc/examples/flutter_graphql_jobs/lib/api/job_api_client.dart', 'repo_id': 'bloc', 'token_count': 355} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_infinite_list/posts/posts.dart';
class PostsList extends StatefulWidget {
const PostsList({super.key});
@override
State<PostsList> createState() => _PostsListState();
}
class _PostsListState extends State<PostsList> {
final _scrollController = ScrollController();
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
}
@override
Widget build(BuildContext context) {
return BlocBuilder<PostBloc, PostState>(
builder: (context, state) {
switch (state.status) {
case PostStatus.failure:
return const Center(child: Text('failed to fetch posts'));
case PostStatus.success:
if (state.posts.isEmpty) {
return const Center(child: Text('no posts'));
}
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return index >= state.posts.length
? const BottomLoader()
: PostListItem(post: state.posts[index]);
},
itemCount: state.hasReachedMax
? state.posts.length
: state.posts.length + 1,
controller: _scrollController,
);
case PostStatus.initial:
return const Center(child: CircularProgressIndicator());
}
},
);
}
@override
void dispose() {
_scrollController
..removeListener(_onScroll)
..dispose();
super.dispose();
}
void _onScroll() {
if (_isBottom) context.read<PostBloc>().add(PostFetched());
}
bool get _isBottom {
if (!_scrollController.hasClients) return false;
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.offset;
return currentScroll >= (maxScroll * 0.9);
}
}
| bloc/examples/flutter_infinite_list/lib/posts/view/posts_list.dart/0 | {'file_path': 'bloc/examples/flutter_infinite_list/lib/posts/view/posts_list.dart', 'repo_id': 'bloc', 'token_count': 819} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_infinite_list/posts/models/models.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Post', () {
test('supports value comparison', () {
expect(
Post(id: 1, title: 'post title', body: 'post body'),
Post(id: 1, title: 'post title', body: 'post body'),
);
});
});
}
| bloc/examples/flutter_infinite_list/test/posts/models/post_test.dart/0 | {'file_path': 'bloc/examples/flutter_infinite_list/test/posts/models/post_test.dart', 'repo_id': 'bloc', 'token_count': 158} |
part of 'authentication_bloc.dart';
class AuthenticationState extends Equatable {
const AuthenticationState._({
this.status = AuthenticationStatus.unknown,
this.user = User.empty,
});
const AuthenticationState.unknown() : this._();
const AuthenticationState.authenticated(User user)
: this._(status: AuthenticationStatus.authenticated, user: user);
const AuthenticationState.unauthenticated()
: this._(status: AuthenticationStatus.unauthenticated);
final AuthenticationStatus status;
final User user;
@override
List<Object> get props => [status, user];
}
| bloc/examples/flutter_login/lib/authentication/bloc/authentication_state.dart/0 | {'file_path': 'bloc/examples/flutter_login/lib/authentication/bloc/authentication_state.dart', 'repo_id': 'bloc', 'token_count': 166} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_login/authentication/authentication.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:user_repository/user_repository.dart';
class MockUser extends Mock implements User {}
void main() {
group('AuthenticationState', () {
group('AuthenticationState.unknown', () {
test('supports value comparisons', () {
expect(
AuthenticationState.unknown(),
AuthenticationState.unknown(),
);
});
});
group('AuthenticationState.authenticated', () {
test('supports value comparisons', () {
final user = MockUser();
expect(
AuthenticationState.authenticated(user),
AuthenticationState.authenticated(user),
);
});
});
group('AuthenticationState.unauthenticated', () {
test('supports value comparisons', () {
expect(
AuthenticationState.unauthenticated(),
AuthenticationState.unauthenticated(),
);
});
});
});
}
| bloc/examples/flutter_login/test/authentication/authentication_state_test.dart/0 | {'file_path': 'bloc/examples/flutter_login/test/authentication/authentication_state_test.dart', 'repo_id': 'bloc', 'token_count': 415} |
part of 'cart_bloc.dart';
@immutable
abstract class CartEvent extends Equatable {
const CartEvent();
}
class CartStarted extends CartEvent {
@override
List<Object> get props => [];
}
class CartItemAdded extends CartEvent {
const CartItemAdded(this.item);
final Item item;
@override
List<Object> get props => [item];
}
class CartItemRemoved extends CartEvent {
const CartItemRemoved(this.item);
final Item item;
@override
List<Object> get props => [item];
}
| bloc/examples/flutter_shopping_cart/lib/cart/bloc/cart_event.dart/0 | {'file_path': 'bloc/examples/flutter_shopping_cart/lib/cart/bloc/cart_event.dart', 'repo_id': 'bloc', 'token_count': 154} |
import 'dart:developer';
import 'package:bloc/bloc.dart';
class SimpleBlocObserver extends BlocObserver {
const SimpleBlocObserver();
@override
void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
super.onEvent(bloc, event);
log('${bloc.runtimeType} $event');
}
@override
void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
log('${bloc.runtimeType} $error');
super.onError(bloc, error, stackTrace);
}
@override
void onTransition(
Bloc<dynamic, dynamic> bloc,
Transition<dynamic, dynamic> transition,
) {
super.onTransition(bloc, transition);
log('$transition');
}
}
| bloc/examples/flutter_shopping_cart/lib/simple_bloc_observer.dart/0 | {'file_path': 'bloc/examples/flutter_shopping_cart/lib/simple_bloc_observer.dart', 'repo_id': 'bloc', 'token_count': 247} |
import 'package:flutter_shopping_cart/catalog/catalog.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Item', () {
test('supports value comparison', () async {
expect(Item(1, 'item #1'), Item(1, 'item #1'));
});
});
}
| bloc/examples/flutter_shopping_cart/test/catalog/models/item_test.dart/0 | {'file_path': 'bloc/examples/flutter_shopping_cart/test/catalog/models/item_test.dart', 'repo_id': 'bloc', 'token_count': 105} |
export 'bloc/timer_bloc.dart';
export 'view/timer_page.dart';
| bloc/examples/flutter_timer/lib/timer/timer.dart/0 | {'file_path': 'bloc/examples/flutter_timer/lib/timer/timer.dart', 'repo_id': 'bloc', 'token_count': 26} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_todos/edit_todo/edit_todo.dart';
import 'package:flutter_todos/home/home.dart';
import 'package:flutter_todos/stats/stats.dart';
import 'package:flutter_todos/todos_overview/todos_overview.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => HomeCubit(),
child: const HomeView(),
);
}
}
class HomeView extends StatelessWidget {
const HomeView({super.key});
@override
Widget build(BuildContext context) {
final selectedTab = context.select((HomeCubit cubit) => cubit.state.tab);
return Scaffold(
body: IndexedStack(
index: selectedTab.index,
children: const [TodosOverviewPage(), StatsPage()],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
key: const Key('homeView_addTodo_floatingActionButton'),
onPressed: () => Navigator.of(context).push(EditTodoPage.route()),
child: const Icon(Icons.add),
),
bottomNavigationBar: BottomAppBar(
shape: const CircularNotchedRectangle(),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_HomeTabButton(
groupValue: selectedTab,
value: HomeTab.todos,
icon: const Icon(Icons.list_rounded),
),
_HomeTabButton(
groupValue: selectedTab,
value: HomeTab.stats,
icon: const Icon(Icons.show_chart_rounded),
),
],
),
),
);
}
}
class _HomeTabButton extends StatelessWidget {
const _HomeTabButton({
required this.groupValue,
required this.value,
required this.icon,
});
final HomeTab groupValue;
final HomeTab value;
final Widget icon;
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: () => context.read<HomeCubit>().setTab(value),
iconSize: 32,
color:
groupValue != value ? null : Theme.of(context).colorScheme.secondary,
icon: icon,
);
}
}
| bloc/examples/flutter_todos/lib/home/view/home_page.dart/0 | {'file_path': 'bloc/examples/flutter_todos/lib/home/view/home_page.dart', 'repo_id': 'bloc', 'token_count': 959} |
part of 'todos_overview_bloc.dart';
enum TodosOverviewStatus { initial, loading, success, failure }
class TodosOverviewState extends Equatable {
const TodosOverviewState({
this.status = TodosOverviewStatus.initial,
this.todos = const [],
this.filter = TodosViewFilter.all,
this.lastDeletedTodo,
});
final TodosOverviewStatus status;
final List<Todo> todos;
final TodosViewFilter filter;
final Todo? lastDeletedTodo;
Iterable<Todo> get filteredTodos => filter.applyAll(todos);
TodosOverviewState copyWith({
TodosOverviewStatus Function()? status,
List<Todo> Function()? todos,
TodosViewFilter Function()? filter,
Todo? Function()? lastDeletedTodo,
}) {
return TodosOverviewState(
status: status != null ? status() : this.status,
todos: todos != null ? todos() : this.todos,
filter: filter != null ? filter() : this.filter,
lastDeletedTodo:
lastDeletedTodo != null ? lastDeletedTodo() : this.lastDeletedTodo,
);
}
@override
List<Object?> get props => [
status,
todos,
filter,
lastDeletedTodo,
];
}
| bloc/examples/flutter_todos/lib/todos_overview/bloc/todos_overview_state.dart/0 | {'file_path': 'bloc/examples/flutter_todos/lib/todos_overview/bloc/todos_overview_state.dart', 'repo_id': 'bloc', 'token_count': 450} |
// ignore_for_file: prefer_const_constructors
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:local_storage_todos_api/local_storage_todos_api.dart';
import 'package:mocktail/mocktail.dart';
import 'package:todos_api/todos_api.dart';
class MockSharedPreferences extends Mock implements SharedPreferences {}
void main() {
group('LocalStorageTodosApi', () {
late SharedPreferences plugin;
final todos = [
Todo(
id: '1',
title: 'title 1',
description: 'description 1',
),
Todo(
id: '2',
title: 'title 2',
description: 'description 2',
),
Todo(
id: '3',
title: 'title 3',
description: 'description 3',
isCompleted: true,
),
];
setUp(() {
plugin = MockSharedPreferences();
when(() => plugin.getString(any())).thenReturn(json.encode(todos));
when(() => plugin.setString(any(), any())).thenAnswer((_) async => true);
});
LocalStorageTodosApi createSubject() {
return LocalStorageTodosApi(
plugin: plugin,
);
}
group('constructor', () {
test('works properly', () {
expect(
createSubject,
returnsNormally,
);
});
group('initializes the todos stream', () {
test('with existing todos if present', () {
final subject = createSubject();
expect(subject.getTodos(), emits(todos));
verify(
() => plugin.getString(
LocalStorageTodosApi.kTodosCollectionKey,
),
).called(1);
});
test('with empty list if no todos present', () {
when(() => plugin.getString(any())).thenReturn(null);
final subject = createSubject();
expect(subject.getTodos(), emits(const <Todo>[]));
verify(
() => plugin.getString(
LocalStorageTodosApi.kTodosCollectionKey,
),
).called(1);
});
});
});
test('getTodos returns stream of current list todos', () {
expect(
createSubject().getTodos(),
emits(todos),
);
});
group('saveTodo', () {
test('saves new todos', () {
final newTodo = Todo(
id: '4',
title: 'title 4',
description: 'description 4',
);
final newTodos = [...todos, newTodo];
final subject = createSubject();
expect(subject.saveTodo(newTodo), completes);
expect(subject.getTodos(), emits(newTodos));
verify(
() => plugin.setString(
LocalStorageTodosApi.kTodosCollectionKey,
json.encode(newTodos),
),
).called(1);
});
test('updates existing todos', () {
final updatedTodo = Todo(
id: '1',
title: 'new title 1',
description: 'new description 1',
isCompleted: true,
);
final newTodos = [updatedTodo, ...todos.sublist(1)];
final subject = createSubject();
expect(subject.saveTodo(updatedTodo), completes);
expect(subject.getTodos(), emits(newTodos));
verify(
() => plugin.setString(
LocalStorageTodosApi.kTodosCollectionKey,
json.encode(newTodos),
),
).called(1);
});
});
group('deleteTodo', () {
test('deletes existing todos', () {
final newTodos = todos.sublist(1);
final subject = createSubject();
expect(subject.deleteTodo(todos[0].id), completes);
expect(subject.getTodos(), emits(newTodos));
verify(
() => plugin.setString(
LocalStorageTodosApi.kTodosCollectionKey,
json.encode(newTodos),
),
).called(1);
});
test(
'throws TodoNotFoundException if todo '
'with provided id is not found',
() {
final subject = createSubject();
expect(
() => subject.deleteTodo('non-existing-id'),
throwsA(isA<TodoNotFoundException>()),
);
},
);
});
group('clearCompleted', () {
test('deletes all completed todos', () {
final newTodos = todos.where((todo) => !todo.isCompleted).toList();
final deletedTodosAmount = todos.length - newTodos.length;
final subject = createSubject();
expect(
subject.clearCompleted(),
completion(equals(deletedTodosAmount)),
);
expect(subject.getTodos(), emits(newTodos));
verify(
() => plugin.setString(
LocalStorageTodosApi.kTodosCollectionKey,
json.encode(newTodos),
),
).called(1);
});
});
group('completeAll', () {
test('sets isCompleted on all todos to provided value', () {
final newTodos =
todos.map((todo) => todo.copyWith(isCompleted: true)).toList();
final changedTodosAmount =
todos.where((todo) => !todo.isCompleted).length;
final subject = createSubject();
expect(
subject.completeAll(isCompleted: true),
completion(equals(changedTodosAmount)),
);
expect(subject.getTodos(), emits(newTodos));
verify(
() => plugin.setString(
LocalStorageTodosApi.kTodosCollectionKey,
json.encode(newTodos),
),
).called(1);
});
});
});
}
| bloc/examples/flutter_todos/packages/local_storage_todos_api/test/local_storage_todos_api_test.dart/0 | {'file_path': 'bloc/examples/flutter_todos/packages/local_storage_todos_api/test/local_storage_todos_api_test.dart', 'repo_id': 'bloc', 'token_count': 2631} |
import 'package:todos_api/todos_api.dart';
/// {@template todos_repository}
/// A repository that handles `todo` related requests.
/// {@endtemplate}
class TodosRepository {
/// {@macro todos_repository}
const TodosRepository({
required TodosApi todosApi,
}) : _todosApi = todosApi;
final TodosApi _todosApi;
/// Provides a [Stream] of all todos.
Stream<List<Todo>> getTodos() => _todosApi.getTodos();
/// Saves a [todo].
///
/// If a [todo] with the same id already exists, it will be replaced.
Future<void> saveTodo(Todo todo) => _todosApi.saveTodo(todo);
/// Deletes the `todo` with the given id.
///
/// If no `todo` with the given id exists, a [TodoNotFoundException] error is
/// thrown.
Future<void> deleteTodo(String id) => _todosApi.deleteTodo(id);
/// Deletes all completed todos.
///
/// Returns the number of deleted todos.
Future<int> clearCompleted() => _todosApi.clearCompleted();
/// Sets the `isCompleted` state of all todos to the given value.
///
/// Returns the number of updated todos.
Future<int> completeAll({required bool isCompleted}) =>
_todosApi.completeAll(isCompleted: isCompleted);
}
| bloc/examples/flutter_todos/packages/todos_repository/lib/src/todos_repository.dart/0 | {'file_path': 'bloc/examples/flutter_todos/packages/todos_repository/lib/src/todos_repository.dart', 'repo_id': 'bloc', 'token_count': 425} |
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_todos/home/home.dart';
import 'package:flutter_todos/stats/stats.dart';
import 'package:flutter_todos/todos_overview/todos_overview.dart';
import 'package:mockingjay/mockingjay.dart';
import 'package:todos_repository/todos_repository.dart';
import '../../helpers/helpers.dart';
class MockHomeCubit extends MockCubit<HomeState> implements HomeCubit {}
void main() {
late TodosRepository todosRepository;
group('HomePage', () {
setUp(() {
todosRepository = MockTodosRepository();
when(todosRepository.getTodos).thenAnswer((_) => const Stream.empty());
});
testWidgets('renders HomeView', (tester) async {
await tester.pumpApp(
const HomePage(),
todosRepository: todosRepository,
);
expect(find.byType(HomeView), findsOneWidget);
});
});
group('HomeView', () {
const addTodoFloatingActionButtonKey = Key(
'homeView_addTodo_floatingActionButton',
);
late MockNavigator navigator;
late HomeCubit cubit;
setUp(() {
navigator = MockNavigator();
when(() => navigator.push<void>(any())).thenAnswer((_) async {});
cubit = MockHomeCubit();
when(() => cubit.state).thenReturn(const HomeState());
todosRepository = MockTodosRepository();
when(todosRepository.getTodos).thenAnswer((_) => const Stream.empty());
});
Widget buildSubject() {
return MockNavigatorProvider(
navigator: navigator,
child: BlocProvider.value(
value: cubit,
child: const HomeView(),
),
);
}
testWidgets(
'renders TodosOverviewPage '
'when tab is set to HomeTab.todos',
(tester) async {
when(() => cubit.state).thenReturn(const HomeState());
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
expect(find.byType(TodosOverviewPage), findsOneWidget);
},
);
testWidgets(
'renders StatsPage '
'when tab is set to HomeTab.stats',
(tester) async {
when(() => cubit.state).thenReturn(const HomeState(tab: HomeTab.stats));
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
expect(find.byType(StatsPage), findsOneWidget);
},
);
testWidgets(
'calls setTab with HomeTab.todos on HomeCubit '
'when todos navigation button is pressed',
(tester) async {
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
await tester.tap(find.byIcon(Icons.list_rounded));
verify(() => cubit.setTab(HomeTab.todos)).called(1);
},
);
testWidgets(
'calls setTab with HomeTab.stats on HomeCubit '
'when stats navigation button is pressed',
(tester) async {
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
await tester.tap(find.byIcon(Icons.show_chart_rounded));
verify(() => cubit.setTab(HomeTab.stats)).called(1);
},
);
group('add todo floating action button', () {
testWidgets(
'is rendered',
(tester) async {
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
expect(
find.byKey(addTodoFloatingActionButtonKey),
findsOneWidget,
);
final addTodoFloatingActionButton =
tester.widget(find.byKey(addTodoFloatingActionButtonKey));
expect(
addTodoFloatingActionButton,
isA<FloatingActionButton>(),
);
},
);
testWidgets('renders add icon', (tester) async {
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
expect(
find.descendant(
of: find.byKey(addTodoFloatingActionButtonKey),
matching: find.byIcon(Icons.add),
),
findsOneWidget,
);
});
testWidgets(
'navigates to the EditTodoPage when pressed',
(tester) async {
await tester.pumpApp(
buildSubject(),
todosRepository: todosRepository,
);
await tester.tap(find.byKey(addTodoFloatingActionButtonKey));
verify(
() => navigator.push<void>(any(that: isRoute<void>())),
).called(1);
},
);
});
});
}
| bloc/examples/flutter_todos/test/home/view/home_page_test.dart/0 | {'file_path': 'bloc/examples/flutter_todos/test/home/view/home_page_test.dart', 'repo_id': 'bloc', 'token_count': 2166} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'weather_cubit.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
WeatherState _$WeatherStateFromJson(Map<String, dynamic> json) =>
$checkedCreate(
'WeatherState',
json,
($checkedConvert) {
final val = WeatherState(
status: $checkedConvert(
'status',
(v) =>
$enumDecodeNullable(_$WeatherStatusEnumMap, v) ??
WeatherStatus.initial),
temperatureUnits: $checkedConvert(
'temperature_units',
(v) =>
$enumDecodeNullable(_$TemperatureUnitsEnumMap, v) ??
TemperatureUnits.celsius),
weather: $checkedConvert(
'weather',
(v) => v == null
? null
: Weather.fromJson(v as Map<String, dynamic>)),
);
return val;
},
fieldKeyMap: const {'temperatureUnits': 'temperature_units'},
);
Map<String, dynamic> _$WeatherStateToJson(WeatherState instance) =>
<String, dynamic>{
'status': _$WeatherStatusEnumMap[instance.status]!,
'weather': instance.weather.toJson(),
'temperature_units':
_$TemperatureUnitsEnumMap[instance.temperatureUnits]!,
};
const _$WeatherStatusEnumMap = {
WeatherStatus.initial: 'initial',
WeatherStatus.loading: 'loading',
WeatherStatus.success: 'success',
WeatherStatus.failure: 'failure',
};
const _$TemperatureUnitsEnumMap = {
TemperatureUnits.fahrenheit: 'fahrenheit',
TemperatureUnits.celsius: 'celsius',
};
| bloc/examples/flutter_weather/lib/weather/cubit/weather_cubit.g.dart/0 | {'file_path': 'bloc/examples/flutter_weather/lib/weather/cubit/weather_cubit.g.dart', 'repo_id': 'bloc', 'token_count': 733} |
targets:
$default:
builders:
json_serializable:
options:
field_rename: snake
checked: true
| bloc/examples/flutter_weather/packages/weather_repository/build.yaml/0 | {'file_path': 'bloc/examples/flutter_weather/packages/weather_repository/build.yaml', 'repo_id': 'bloc', 'token_count': 66} |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_weather/weather/weather.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import 'package:weather_repository/weather_repository.dart'
as weather_repository;
import '../../helpers/hydrated_bloc.dart';
const weatherLocation = 'London';
const weatherCondition = weather_repository.WeatherCondition.rainy;
const weatherTemperature = 9.8;
class MockWeatherRepository extends Mock
implements weather_repository.WeatherRepository {}
class MockWeather extends Mock implements weather_repository.Weather {}
void main() {
initHydratedStorage();
group('WeatherCubit', () {
late weather_repository.Weather weather;
late weather_repository.WeatherRepository weatherRepository;
late WeatherCubit weatherCubit;
setUp(() async {
weather = MockWeather();
weatherRepository = MockWeatherRepository();
when(() => weather.condition).thenReturn(weatherCondition);
when(() => weather.location).thenReturn(weatherLocation);
when(() => weather.temperature).thenReturn(weatherTemperature);
when(
() => weatherRepository.getWeather(any()),
).thenAnswer((_) async => weather);
weatherCubit = WeatherCubit(weatherRepository);
});
test('initial state is correct', () {
final weatherCubit = WeatherCubit(weatherRepository);
expect(weatherCubit.state, WeatherState());
});
group('toJson/fromJson', () {
test('work properly', () {
final weatherCubit = WeatherCubit(weatherRepository);
expect(
weatherCubit.fromJson(weatherCubit.toJson(weatherCubit.state)),
weatherCubit.state,
);
});
});
group('fetchWeather', () {
blocTest<WeatherCubit, WeatherState>(
'emits nothing when city is null',
build: () => weatherCubit,
act: (cubit) => cubit.fetchWeather(null),
expect: () => <WeatherState>[],
);
blocTest<WeatherCubit, WeatherState>(
'emits nothing when city is empty',
build: () => weatherCubit,
act: (cubit) => cubit.fetchWeather(''),
expect: () => <WeatherState>[],
);
blocTest<WeatherCubit, WeatherState>(
'calls getWeather with correct city',
build: () => weatherCubit,
act: (cubit) => cubit.fetchWeather(weatherLocation),
verify: (_) {
verify(() => weatherRepository.getWeather(weatherLocation)).called(1);
},
);
blocTest<WeatherCubit, WeatherState>(
'emits [loading, failure] when getWeather throws',
setUp: () {
when(
() => weatherRepository.getWeather(any()),
).thenThrow(Exception('oops'));
},
build: () => weatherCubit,
act: (cubit) => cubit.fetchWeather(weatherLocation),
expect: () => <WeatherState>[
WeatherState(status: WeatherStatus.loading),
WeatherState(status: WeatherStatus.failure),
],
);
blocTest<WeatherCubit, WeatherState>(
'emits [loading, success] when getWeather returns (celsius)',
build: () => weatherCubit,
act: (cubit) => cubit.fetchWeather(weatherLocation),
expect: () => <dynamic>[
WeatherState(status: WeatherStatus.loading),
isA<WeatherState>()
.having((w) => w.status, 'status', WeatherStatus.success)
.having(
(w) => w.weather,
'weather',
isA<Weather>()
.having((w) => w.lastUpdated, 'lastUpdated', isNotNull)
.having((w) => w.condition, 'condition', weatherCondition)
.having(
(w) => w.temperature,
'temperature',
Temperature(value: weatherTemperature),
)
.having((w) => w.location, 'location', weatherLocation),
),
],
);
blocTest<WeatherCubit, WeatherState>(
'emits [loading, success] when getWeather returns (fahrenheit)',
build: () => weatherCubit,
seed: () => WeatherState(temperatureUnits: TemperatureUnits.fahrenheit),
act: (cubit) => cubit.fetchWeather(weatherLocation),
expect: () => <dynamic>[
WeatherState(
status: WeatherStatus.loading,
temperatureUnits: TemperatureUnits.fahrenheit,
),
isA<WeatherState>()
.having((w) => w.status, 'status', WeatherStatus.success)
.having(
(w) => w.weather,
'weather',
isA<Weather>()
.having((w) => w.lastUpdated, 'lastUpdated', isNotNull)
.having((w) => w.condition, 'condition', weatherCondition)
.having(
(w) => w.temperature,
'temperature',
Temperature(value: weatherTemperature.toFahrenheit()),
)
.having((w) => w.location, 'location', weatherLocation),
),
],
);
});
group('refreshWeather', () {
blocTest<WeatherCubit, WeatherState>(
'emits nothing when status is not success',
build: () => weatherCubit,
act: (cubit) => cubit.refreshWeather(),
expect: () => <WeatherState>[],
verify: (_) {
verifyNever(() => weatherRepository.getWeather(any()));
},
);
blocTest<WeatherCubit, WeatherState>(
'emits nothing when location is null',
build: () => weatherCubit,
seed: () => WeatherState(status: WeatherStatus.success),
act: (cubit) => cubit.refreshWeather(),
expect: () => <WeatherState>[],
verify: (_) {
verifyNever(() => weatherRepository.getWeather(any()));
},
);
blocTest<WeatherCubit, WeatherState>(
'invokes getWeather with correct location',
build: () => weatherCubit,
seed: () => WeatherState(
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: weatherTemperature),
lastUpdated: DateTime(2020),
condition: weatherCondition,
),
),
act: (cubit) => cubit.refreshWeather(),
verify: (_) {
verify(() => weatherRepository.getWeather(weatherLocation)).called(1);
},
);
blocTest<WeatherCubit, WeatherState>(
'emits nothing when exception is thrown',
setUp: () {
when(
() => weatherRepository.getWeather(any()),
).thenThrow(Exception('oops'));
},
build: () => weatherCubit,
seed: () => WeatherState(
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: weatherTemperature),
lastUpdated: DateTime(2020),
condition: weatherCondition,
),
),
act: (cubit) => cubit.refreshWeather(),
expect: () => <WeatherState>[],
);
blocTest<WeatherCubit, WeatherState>(
'emits updated weather (celsius)',
build: () => weatherCubit,
seed: () => WeatherState(
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: 0),
lastUpdated: DateTime(2020),
condition: weatherCondition,
),
),
act: (cubit) => cubit.refreshWeather(),
expect: () => <Matcher>[
isA<WeatherState>()
.having((w) => w.status, 'status', WeatherStatus.success)
.having(
(w) => w.weather,
'weather',
isA<Weather>()
.having((w) => w.lastUpdated, 'lastUpdated', isNotNull)
.having((w) => w.condition, 'condition', weatherCondition)
.having(
(w) => w.temperature,
'temperature',
Temperature(value: weatherTemperature),
)
.having((w) => w.location, 'location', weatherLocation),
),
],
);
blocTest<WeatherCubit, WeatherState>(
'emits updated weather (fahrenheit)',
build: () => weatherCubit,
seed: () => WeatherState(
temperatureUnits: TemperatureUnits.fahrenheit,
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: 0),
lastUpdated: DateTime(2020),
condition: weatherCondition,
),
),
act: (cubit) => cubit.refreshWeather(),
expect: () => <Matcher>[
isA<WeatherState>()
.having((w) => w.status, 'status', WeatherStatus.success)
.having(
(w) => w.weather,
'weather',
isA<Weather>()
.having((w) => w.lastUpdated, 'lastUpdated', isNotNull)
.having((w) => w.condition, 'condition', weatherCondition)
.having(
(w) => w.temperature,
'temperature',
Temperature(value: weatherTemperature.toFahrenheit()),
)
.having((w) => w.location, 'location', weatherLocation),
),
],
);
});
group('toggleUnits', () {
blocTest<WeatherCubit, WeatherState>(
'emits updated units when status is not success',
build: () => weatherCubit,
act: (cubit) => cubit.toggleUnits(),
expect: () => <WeatherState>[
WeatherState(temperatureUnits: TemperatureUnits.fahrenheit),
],
);
blocTest<WeatherCubit, WeatherState>(
'emits updated units and temperature '
'when status is success (celsius)',
build: () => weatherCubit,
seed: () => WeatherState(
status: WeatherStatus.success,
temperatureUnits: TemperatureUnits.fahrenheit,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: weatherTemperature),
lastUpdated: DateTime(2020),
condition: WeatherCondition.rainy,
),
),
act: (cubit) => cubit.toggleUnits(),
expect: () => <WeatherState>[
WeatherState(
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: weatherTemperature.toCelsius()),
lastUpdated: DateTime(2020),
condition: WeatherCondition.rainy,
),
),
],
);
blocTest<WeatherCubit, WeatherState>(
'emits updated units and temperature '
'when status is success (fahrenheit)',
build: () => weatherCubit,
seed: () => WeatherState(
status: WeatherStatus.success,
weather: Weather(
location: weatherLocation,
temperature: Temperature(value: weatherTemperature),
lastUpdated: DateTime(2020),
condition: WeatherCondition.rainy,
),
),
act: (cubit) => cubit.toggleUnits(),
expect: () => <WeatherState>[
WeatherState(
status: WeatherStatus.success,
temperatureUnits: TemperatureUnits.fahrenheit,
weather: Weather(
location: weatherLocation,
temperature: Temperature(
value: weatherTemperature.toFahrenheit(),
),
lastUpdated: DateTime(2020),
condition: WeatherCondition.rainy,
),
),
],
);
});
});
}
extension on double {
double toFahrenheit() => (this * 9 / 5) + 32;
double toCelsius() => (this - 32) * 5 / 9;
}
| bloc/examples/flutter_weather/test/weather/cubit/weather_cubit_test.dart/0 | {'file_path': 'bloc/examples/flutter_weather/test/weather/cubit/weather_cubit_test.dart', 'repo_id': 'bloc', 'token_count': 5655} |
import 'package:flow_builder/flow_builder.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_wizard/bloc/profile_wizard_bloc.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => const MaterialApp(home: Home());
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: Builder(
builder: (context) {
return ElevatedButton(
onPressed: () async {
final profile = await Navigator.of(context).push(
ProfileWizard.route(),
);
if (!mounted) return;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$profile')));
},
child: const Text('Start Profile Wizard'),
);
},
),
),
);
}
}
class ProfileWizard extends StatelessWidget {
const ProfileWizard({super.key});
static Route<Profile> route() {
return MaterialPageRoute(builder: (_) => const ProfileWizard());
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => ProfileWizardBloc(),
child: ProfileWizardFlow(
onComplete: (profile) => Navigator.of(context).pop(profile),
),
);
}
}
class ProfileWizardFlow extends StatelessWidget {
const ProfileWizardFlow({
super.key,
required this.onComplete,
});
final ValueSetter<Profile> onComplete;
@override
Widget build(BuildContext context) {
return BlocListener<ProfileWizardBloc, ProfileWizardState>(
listenWhen: (_, state) => state.profile.isComplete,
listener: (context, state) => onComplete(state.profile),
child: FlowBuilder<ProfileWizardState>(
state: context.watch<ProfileWizardBloc>().state,
onGeneratePages: (state, pages) {
return [
ProfileNameForm.page(),
if (state.profile.name != null) ProfileAgeForm.page(),
];
},
),
);
}
}
class ProfileNameForm extends StatefulWidget {
const ProfileNameForm({super.key});
static Page<void> page() {
return const MaterialPage<void>(child: ProfileNameForm());
}
@override
State<ProfileNameForm> createState() => _ProfileNameFormState();
}
class _ProfileNameFormState extends State<ProfileNameForm> {
var _name = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Name')),
body: Center(
child: Column(
children: <Widget>[
TextField(
onChanged: (value) => setState(() => _name = value),
decoration: const InputDecoration(
labelText: 'Name',
hintText: 'John Doe',
),
),
ElevatedButton(
onPressed: _name.isNotEmpty
? () => context
.read<ProfileWizardBloc>()
.add(ProfileWizardNameSubmitted(_name))
: null,
child: const Text('Continue'),
)
],
),
),
);
}
}
class ProfileAgeForm extends StatefulWidget {
const ProfileAgeForm({super.key});
static Page<void> page() => const MaterialPage<void>(child: ProfileAgeForm());
@override
State<ProfileAgeForm> createState() => _ProfileAgeFormState();
}
class _ProfileAgeFormState extends State<ProfileAgeForm> {
int? _age;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Age')),
body: Center(
child: Column(
children: <Widget>[
TextField(
onChanged: (value) => setState(() => _age = int.parse(value)),
decoration: const InputDecoration(
labelText: 'Age',
hintText: '42',
),
keyboardType: TextInputType.number,
),
ElevatedButton(
onPressed: _age != null
? () => context
.read<ProfileWizardBloc>()
.add(ProfileWizardAgeSubmitted(_age))
: null,
child: const Text('Continue'),
)
],
),
),
);
}
}
extension on Profile {
bool get isComplete => name != null && age != null;
}
| bloc/examples/flutter_wizard/lib/main.dart/0 | {'file_path': 'bloc/examples/flutter_wizard/lib/main.dart', 'repo_id': 'bloc', 'token_count': 2134} |
import 'package:common_github_search/common_github_search.dart';
import 'package:ngdart/angular.dart';
@Component(
selector: 'search-bar',
templateUrl: 'search_bar_component.html',
)
class SearchBarComponent {
@Input()
late GithubSearchBloc githubSearchBloc;
void onTextChanged(String text) {
githubSearchBloc.add(TextChanged(text: text));
}
}
| bloc/examples/github_search/angular_github_search/lib/src/search_form/search_bar/search_bar_component.dart/0 | {'file_path': 'bloc/examples/github_search/angular_github_search/lib/src/search_form/search_bar/search_bar_component.dart', 'repo_id': 'bloc', 'token_count': 121} |
part of 'bloc.dart';
/// {@template emitter}
/// An [Emitter] is a class which is capable of emitting new states.
///
/// See also:
///
/// * [EventHandler] which has access to an [Emitter].
///
/// {@endtemplate}
abstract class Emitter<State> {
/// Subscribes to the provided [stream] and invokes the [onData] callback
/// when the [stream] emits new data.
///
/// [onEach] completes when the event handler is cancelled or when
/// the provided [stream] has ended.
///
/// If [onError] is omitted, any errors on this [stream]
/// are considered unhandled, and will be thrown by [onEach].
/// As a result, the internal subscription to the [stream] will be canceled.
///
/// If [onError] is provided, any errors on this [stream] will be passed on to
/// [onError] and will not result in unhandled exceptions or cancelations to
/// the internal stream subscription.
///
/// **Note**: The stack trace argument may be [StackTrace.empty]
/// if the [stream] received an error without a stack trace.
Future<void> onEach<T>(
Stream<T> stream, {
required void Function(T data) onData,
void Function(Object error, StackTrace stackTrace)? onError,
});
/// Subscribes to the provided [stream] and invokes the [onData] callback
/// when the [stream] emits new data and the result of [onData] is emitted.
///
/// [forEach] completes when the event handler is cancelled or when
/// the provided [stream] has ended.
///
/// If [onError] is omitted, any errors on this [stream]
/// are considered unhandled, and will be thrown by [forEach].
/// As a result, the internal subscription to the [stream] will be canceled.
///
/// If [onError] is provided, any errors on this [stream] will be passed on to
/// [onError] and will not result in unhandled exceptions or cancelations to
/// the internal stream subscription.
///
/// **Note**: The stack trace argument may be [StackTrace.empty]
/// if the [stream] received an error without a stack trace.
Future<void> forEach<T>(
Stream<T> stream, {
required State Function(T data) onData,
State Function(Object error, StackTrace stackTrace)? onError,
});
/// Whether the [EventHandler] associated with this [Emitter]
/// has been completed or canceled.
bool get isDone;
/// Emits the provided [state].
void call(State state);
}
class _Emitter<State> implements Emitter<State> {
_Emitter(this._emit);
final void Function(State state) _emit;
final _completer = Completer<void>();
final _disposables = <FutureOr<void> Function()>[];
var _isCanceled = false;
var _isCompleted = false;
@override
Future<void> onEach<T>(
Stream<T> stream, {
required void Function(T data) onData,
void Function(Object error, StackTrace stackTrace)? onError,
}) {
final completer = Completer<void>();
final subscription = stream.listen(
onData,
onDone: completer.complete,
onError: onError ?? completer.completeError,
cancelOnError: onError == null,
);
_disposables.add(subscription.cancel);
return Future.any([future, completer.future]).whenComplete(() {
subscription.cancel();
_disposables.remove(subscription.cancel);
});
}
@override
Future<void> forEach<T>(
Stream<T> stream, {
required State Function(T data) onData,
State Function(Object error, StackTrace stackTrace)? onError,
}) {
return onEach<T>(
stream,
onData: (data) => call(onData(data)),
onError: onError != null
? (Object error, StackTrace stackTrace) {
call(onError(error, stackTrace));
}
: null,
);
}
@override
void call(State state) {
assert(
!_isCompleted,
'''\n\n
emit was called after an event handler completed normally.
This is usually due to an unawaited future in an event handler.
Please make sure to await all asynchronous operations with event handlers
and use emit.isDone after asynchronous operations before calling emit() to
ensure the event handler has not completed.
**BAD**
on<Event>((event, emit) {
future.whenComplete(() => emit(...));
});
**GOOD**
on<Event>((event, emit) async {
await future.whenComplete(() => emit(...));
});
''',
);
if (!_isCanceled) _emit(state);
}
@override
bool get isDone => _isCanceled || _isCompleted;
void cancel() {
if (isDone) return;
_isCanceled = true;
_close();
}
void complete() {
if (isDone) return;
assert(
_disposables.isEmpty,
'''\n\n
An event handler completed but left pending subscriptions behind.
This is most likely due to an unawaited emit.forEach or emit.onEach.
Please make sure to await all asynchronous operations within event handlers.
**BAD**
on<Event>((event, emit) {
emit.forEach(...);
});
**GOOD**
on<Event>((event, emit) async {
await emit.forEach(...);
});
**GOOD**
on<Event>((event, emit) {
return emit.forEach(...);
});
**GOOD**
on<Event>((event, emit) => emit.forEach(...));
''',
);
_isCompleted = true;
_close();
}
void _close() {
for (final disposable in _disposables) {
disposable.call();
}
_disposables.clear();
if (!_completer.isCompleted) _completer.complete();
}
Future<void> get future => _completer.future;
}
| bloc/packages/bloc/lib/src/emitter.dart/0 | {'file_path': 'bloc/packages/bloc/lib/src/emitter.dart', 'repo_id': 'bloc', 'token_count': 1818} |
part of 'complex_bloc.dart';
@immutable
abstract class ComplexEvent {}
class ComplexEventA extends ComplexEvent {
@override
bool operator ==(
Object other,
) =>
identical(
this,
other,
) ||
other is ComplexEventA && runtimeType == other.runtimeType;
@override
int get hashCode => 0;
}
class ComplexEventB extends ComplexEvent {
@override
bool operator ==(
Object other,
) =>
identical(
this,
other,
) ||
other is ComplexEventB && runtimeType == other.runtimeType;
@override
int get hashCode => 1;
}
class ComplexEventC extends ComplexEvent {
@override
bool operator ==(
Object other,
) =>
identical(
this,
other,
) ||
other is ComplexEventC && runtimeType == other.runtimeType;
@override
int get hashCode => 2;
}
class ComplexEventD extends ComplexEvent {
@override
bool operator ==(
Object other,
) =>
identical(
this,
other,
) ||
other is ComplexEventD && runtimeType == other.runtimeType;
@override
int get hashCode => 3;
}
| bloc/packages/bloc/test/blocs/complex/complex_event.dart/0 | {'file_path': 'bloc/packages/bloc/test/blocs/complex/complex_event.dart', 'repo_id': 'bloc', 'token_count': 440} |
import 'dart:async';
import 'package:bloc/bloc.dart';
class UnawaitedEvent {}
class UnawaitedState {}
class UnawaitedBloc extends Bloc<UnawaitedEvent, UnawaitedState> {
UnawaitedBloc(Future<void> future) : super(UnawaitedState()) {
on<UnawaitedEvent>((event, emit) {
future.whenComplete(() => emit(UnawaitedState()));
});
}
}
| bloc/packages/bloc/test/blocs/unawaited/unawaited_bloc.dart/0 | {'file_path': 'bloc/packages/bloc/test/blocs/unawaited/unawaited_bloc.dart', 'repo_id': 'bloc', 'token_count': 125} |
import 'dart:async';
import 'package:bloc/bloc.dart';
/// Process only one event and ignore (drop) any new events
/// until the current event is done.
///
/// **Note**: dropped events never trigger the event handler.
EventTransformer<Event> droppable<Event>() {
return (events, mapper) {
return events.transform(_ExhaustMapStreamTransformer(mapper));
};
}
class _ExhaustMapStreamTransformer<T> extends StreamTransformerBase<T, T> {
_ExhaustMapStreamTransformer(this.mapper);
final EventMapper<T> mapper;
@override
Stream<T> bind(Stream<T> stream) {
late StreamSubscription<T> subscription;
StreamSubscription<T>? mappedSubscription;
final controller = StreamController<T>(
onCancel: () async {
await mappedSubscription?.cancel();
return subscription.cancel();
},
sync: true,
);
subscription = stream.listen(
(data) {
if (mappedSubscription != null) return;
final Stream<T> mappedStream;
mappedStream = mapper(data);
mappedSubscription = mappedStream.listen(
controller.add,
onError: controller.addError,
onDone: () => mappedSubscription = null,
);
},
onError: controller.addError,
onDone: () => mappedSubscription ?? controller.close(),
);
return controller.stream;
}
}
| bloc/packages/bloc_concurrency/lib/src/droppable.dart/0 | {'file_path': 'bloc/packages/bloc_concurrency/lib/src/droppable.dart', 'repo_id': 'bloc', 'token_count': 501} |
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'counter_bloc.dart';
class SumEvent {
const SumEvent(this.value);
final int value;
}
class SumBloc extends Bloc<SumEvent, int> {
SumBloc(CounterBloc counterBloc) : super(0) {
on<SumEvent>((event, emit) => emit(state + event.value));
_countSubscription = counterBloc.stream.listen(
(count) => add(SumEvent(count)),
);
}
late StreamSubscription<int> _countSubscription;
@override
Future<void> close() {
_countSubscription.cancel();
return super.close();
}
}
| bloc/packages/bloc_test/test/blocs/sum_bloc.dart/0 | {'file_path': 'bloc/packages/bloc_test/test/blocs/sum_bloc.dart', 'repo_id': 'bloc', 'token_count': 215} |
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/single_child_widget.dart';
/// Signature for the `listener` function which takes the `BuildContext` along
/// with the `state` and is responsible for executing in response to
/// `state` changes.
typedef BlocWidgetListener<S> = void Function(BuildContext context, S state);
/// Signature for the `listenWhen` function which takes the previous `state`
/// and the current `state` and is responsible for returning a [bool] which
/// determines whether or not to call [BlocWidgetListener] of [BlocListener]
/// with the current `state`.
typedef BlocListenerCondition<S> = bool Function(S previous, S current);
/// {@template bloc_listener}
/// Takes a [BlocWidgetListener] and an optional [bloc] and invokes
/// the [listener] in response to `state` changes in the [bloc].
/// It should be used for functionality that needs to occur only in response to
/// a `state` change such as navigation, showing a `SnackBar`, showing
/// a `Dialog`, etc...
/// The [listener] is guaranteed to only be called once for each `state` change
/// unlike the `builder` in `BlocBuilder`.
///
/// If the [bloc] parameter is omitted, [BlocListener] will automatically
/// perform a lookup using [BlocProvider] and the current `BuildContext`.
///
/// ```dart
/// BlocListener<BlocA, BlocAState>(
/// listener: (context, state) {
/// // do stuff here based on BlocA's state
/// },
/// child: Container(),
/// )
/// ```
/// Only specify the [bloc] if you wish to provide a [bloc] that is otherwise
/// not accessible via [BlocProvider] and the current `BuildContext`.
///
/// ```dart
/// BlocListener<BlocA, BlocAState>(
/// value: blocA,
/// listener: (context, state) {
/// // do stuff here based on BlocA's state
/// },
/// child: Container(),
/// )
/// ```
/// {@endtemplate}
///
/// {@template bloc_listener_listen_when}
/// An optional [listenWhen] can be implemented for more granular control
/// over when [listener] is called.
/// [listenWhen] will be invoked on each [bloc] `state` change.
/// [listenWhen] takes the previous `state` and current `state` and must
/// return a [bool] which determines whether or not the [listener] function
/// will be invoked.
/// The previous `state` will be initialized to the `state` of the [bloc]
/// when the [BlocListener] is initialized.
/// [listenWhen] is optional and if omitted, it will default to `true`.
///
/// ```dart
/// BlocListener<BlocA, BlocAState>(
/// listenWhen: (previous, current) {
/// // return true/false to determine whether or not
/// // to invoke listener with state
/// },
/// listener: (context, state) {
/// // do stuff here based on BlocA's state
/// }
/// child: Container(),
/// )
/// ```
/// {@endtemplate}
class BlocListener<B extends StateStreamable<S>, S>
extends BlocListenerBase<B, S> {
/// {@macro bloc_listener}
/// {@macro bloc_listener_listen_when}
const BlocListener({
Key? key,
required BlocWidgetListener<S> listener,
B? bloc,
BlocListenerCondition<S>? listenWhen,
Widget? child,
}) : super(
key: key,
child: child,
listener: listener,
bloc: bloc,
listenWhen: listenWhen,
);
}
/// {@template bloc_listener_base}
/// Base class for widgets that listen to state changes in a specified [bloc].
///
/// A [BlocListenerBase] is stateful and maintains the state subscription.
/// The type of the state and what happens with each state change
/// is defined by sub-classes.
/// {@endtemplate}
abstract class BlocListenerBase<B extends StateStreamable<S>, S>
extends SingleChildStatefulWidget {
/// {@macro bloc_listener_base}
const BlocListenerBase({
Key? key,
required this.listener,
this.bloc,
this.child,
this.listenWhen,
}) : super(key: key, child: child);
/// The widget which will be rendered as a descendant of the
/// [BlocListenerBase].
final Widget? child;
/// The [bloc] whose `state` will be listened to.
/// Whenever the [bloc]'s `state` changes, [listener] will be invoked.
final B? bloc;
/// The [BlocWidgetListener] which will be called on every `state` change.
/// This [listener] should be used for any code which needs to execute
/// in response to a `state` change.
final BlocWidgetListener<S> listener;
/// {@macro bloc_listener_listen_when}
final BlocListenerCondition<S>? listenWhen;
@override
SingleChildState<BlocListenerBase<B, S>> createState() =>
_BlocListenerBaseState<B, S>();
}
class _BlocListenerBaseState<B extends StateStreamable<S>, S>
extends SingleChildState<BlocListenerBase<B, S>> {
StreamSubscription<S>? _subscription;
late B _bloc;
late S _previousState;
@override
void initState() {
super.initState();
_bloc = widget.bloc ?? context.read<B>();
_previousState = _bloc.state;
_subscribe();
}
@override
void didUpdateWidget(BlocListenerBase<B, S> oldWidget) {
super.didUpdateWidget(oldWidget);
final oldBloc = oldWidget.bloc ?? context.read<B>();
final currentBloc = widget.bloc ?? oldBloc;
if (oldBloc != currentBloc) {
if (_subscription != null) {
_unsubscribe();
_bloc = currentBloc;
_previousState = _bloc.state;
}
_subscribe();
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final bloc = widget.bloc ?? context.read<B>();
if (_bloc != bloc) {
if (_subscription != null) {
_unsubscribe();
_bloc = bloc;
_previousState = _bloc.state;
}
_subscribe();
}
}
@override
Widget buildWithChild(BuildContext context, Widget? child) {
assert(
child != null,
'''${widget.runtimeType} used outside of MultiBlocListener must specify a child''',
);
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 child!;
}
@override
void dispose() {
_unsubscribe();
super.dispose();
}
void _subscribe() {
_subscription = _bloc.stream.listen((state) {
if (widget.listenWhen?.call(_previousState, state) ?? true) {
widget.listener(context, state);
}
_previousState = state;
});
}
void _unsubscribe() {
_subscription?.cancel();
_subscription = null;
}
}
| bloc/packages/flutter_bloc/lib/src/bloc_listener.dart/0 | {'file_path': 'bloc/packages/flutter_bloc/lib/src/bloc_listener.dart', 'repo_id': 'bloc', 'token_count': 2279} |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
class MyApp extends MaterialApp {
MyApp() : super(home: CounterPage());
}
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final repositoryA = RepositoryProvider.of<RepositoryA>(context);
final repositoryB = RepositoryProvider.of<RepositoryB>(context);
return Scaffold(
body: Column(
children: [
Text(
'${repositoryA.data}',
key: const Key('RepositoryA_data'),
),
Text(
'${repositoryB.data}',
key: const Key('RepositoryB_data'),
),
],
),
);
}
}
class RepositoryA {
const RepositoryA(this.data);
final int data;
}
class RepositoryB {
const RepositoryB(this.data);
final int data;
}
void main() {
group('MultiRepositoryProvider', () {
testWidgets('passes values to children', (tester) async {
await tester.pumpWidget(
MultiRepositoryProvider(
providers: [
RepositoryProvider<RepositoryA>(
create: (_) => const RepositoryA(0),
),
RepositoryProvider<RepositoryB>(
create: (_) => const RepositoryB(1),
),
],
child: MyApp(),
),
);
final repositoryAFinder = find.byKey((const Key('RepositoryA_data')));
expect(repositoryAFinder, findsOneWidget);
final repositoryAText = tester.widget(repositoryAFinder) as Text;
expect(repositoryAText.data, '0');
final repositoryBFinder = find.byKey((const Key('RepositoryB_data')));
expect(repositoryBFinder, findsOneWidget);
final repositoryBText = tester.widget(repositoryBFinder) as Text;
expect(repositoryBText.data, '1');
});
testWidgets('passes values to children without explict types',
(tester) async {
await tester.pumpWidget(
MultiRepositoryProvider(
providers: [
RepositoryProvider(
create: (_) => const RepositoryA(0),
),
RepositoryProvider(
create: (_) => const RepositoryB(1),
),
],
child: MyApp(),
),
);
final repositoryAFinder = find.byKey((const Key('RepositoryA_data')));
expect(repositoryAFinder, findsOneWidget);
final repositoryAText = tester.widget(repositoryAFinder) as Text;
expect(repositoryAText.data, '0');
final repositoryBFinder = find.byKey((const Key('RepositoryB_data')));
expect(repositoryBFinder, findsOneWidget);
final repositoryBText = tester.widget(repositoryBFinder) as Text;
expect(repositoryBText.data, '1');
});
});
}
| bloc/packages/flutter_bloc/test/multi_repository_provider_test.dart/0 | {'file_path': 'bloc/packages/flutter_bloc/test/multi_repository_provider_test.dart', 'repo_id': 'bloc', 'token_count': 1219} |
export 'bad_cubit.dart';
export 'cyclic_cubit.dart';
export 'freezed_cubit.dart';
export 'json_serializable_cubit.dart';
export 'list_cubit.dart';
export 'manual_cubit.dart';
export 'simple_cubit.dart';
| bloc/packages/hydrated_bloc/test/cubits/cubits.dart/0 | {'file_path': 'bloc/packages/hydrated_bloc/test/cubits/cubits.dart', 'repo_id': 'bloc', 'token_count': 90} |
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:hive/hive.dart';
// ignore: implementation_imports
import 'package:hive/src/hive_impl.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
class MockBox extends Mock implements Box<dynamic> {}
void main() {
group('HydratedStorage', () {
final cwd = Directory.current.absolute.path;
final storageDirectory = Directory(cwd);
late Storage storage;
tearDown(() async {
await storage.clear();
try {
await HydratedStorage.hive.deleteFromDisk();
} catch (_) {}
});
group('migration', () {
test('returns correct value when file exists', () async {
File('${storageDirectory.path}/.hydrated_bloc.json')
..writeAsStringSync(json.encode({
'CounterBloc': json.encode({'value': 4})
}));
storage = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
expect(storage.read('CounterBloc')['value'] as int, 4);
});
});
group('build', () {
setUp(() async {
final storage = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
await storage.clear();
await storage.close();
});
test('reuses existing instance when called multiple times', () async {
final instanceA = storage = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
final instanceB = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
expect(instanceA, instanceB);
});
test(
'does not call Hive.init '
'when storageDirectory is webStorageDirectory', () async {
final completer = Completer<void>();
await runZonedGuarded(() {
HydratedStorage.build(
storageDirectory: HydratedStorage.webStorageDirectory,
).whenComplete(completer.complete);
return completer.future;
}, (Object _, StackTrace __) {});
expect(HiveImpl().homePath, isNull);
storage = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
});
test('creates internal HiveImpl with correct directory', () async {
storage = await HydratedStorage.build(
storageDirectory: storageDirectory,
);
final box = HydratedStorage.hive.box<dynamic>('hydrated_box');
expect(box, isNotNull);
expect(box.path, p.join(storageDirectory.path, 'hydrated_box.hive'));
});
});
group('default constructor', () {
const key = '__key__';
const value = '__value__';
late Box box;
setUp(() {
box = MockBox();
when(() => box.clear()).thenAnswer((_) async => 0);
when(() => box.close()).thenAnswer((_) async {});
storage = HydratedStorage(box);
});
group('read', () {
test('returns null when box is not open', () {
when(() => box.isOpen).thenReturn(false);
expect(storage.read(key), isNull);
});
test('returns correct value when box is open', () {
when(() => box.isOpen).thenReturn(true);
when<dynamic>(() => box.get(any<dynamic>())).thenReturn(value);
expect(storage.read(key), value);
verify<dynamic>(() => box.get(key)).called(1);
});
});
group('write', () {
test('does nothing when box is not open', () async {
when(() => box.isOpen).thenReturn(false);
await storage.write(key, value);
verifyNever(() => box.put(any<dynamic>(), any<dynamic>()));
});
test('puts key/value in box when box is open', () async {
when(() => box.isOpen).thenReturn(true);
when(
() => box.put(any<dynamic>(), any<dynamic>()),
).thenAnswer((_) => Future<void>.value());
await storage.write(key, value);
verify(() => box.put(key, value)).called(1);
});
});
group('delete', () {
test('does nothing when box is not open', () async {
when(() => box.isOpen).thenReturn(false);
await storage.delete(key);
verifyNever(() => box.delete(any<dynamic>()));
});
test('puts key/value in box when box is open', () async {
when(() => box.isOpen).thenReturn(true);
when(
() => box.delete(any<dynamic>()),
).thenAnswer((_) => Future<void>.value());
await storage.delete(key);
verify(() => box.delete(key)).called(1);
});
});
group('clear', () {
test('does nothing when box is not open', () async {
when(() => box.isOpen).thenReturn(false);
await storage.clear();
verifyNever(() => box.clear());
});
test('clears box when box is open', () async {
when(() => box.isOpen).thenReturn(true);
await storage.clear();
verify(() => box.clear()).called(1);
});
});
});
group('During heavy load', () {
test('writes key/value pairs correctly', () async {
const token = 'token';
storage = await HydratedStorage.build(
storageDirectory: Directory(cwd),
);
await Stream.fromIterable(
Iterable.generate(120, (i) => i),
).asyncMap((i) async {
final record = Iterable.generate(
i,
(i) => Iterable.generate(i, (j) => 'Point($i,$j);').toList(),
).toList();
unawaited(storage.write(token, record));
storage = await HydratedStorage.build(
storageDirectory: Directory(cwd),
);
final written = storage.read(token) as List<List<String>>;
expect(written, isNotNull);
expect(written, record);
}).drain<dynamic>();
});
});
group('Storage interference', () {
final temp = p.join(cwd, 'temp');
final docs = p.join(cwd, 'docs');
tearDown(() async {
await storage.clear();
await storage.close();
await Hive.close();
await Directory(temp).delete(recursive: true);
await Directory(docs).delete(recursive: true);
});
test('Hive and Hydrated default directories', () async {
Hive.init(docs);
storage = await HydratedStorage.build(
storageDirectory: Directory(temp)..createSync(),
);
var box = await Hive.openBox<String>('hive');
await box.put('name', 'hive');
expect(box.get('name'), 'hive');
await Hive.close();
// https://github.com/hivedb/hive/pull/521#issuecomment-767903897
(Hive as HiveImpl).homePath = null;
Hive.init(docs);
box = await Hive.openBox<String>('hive');
expect(box.get('name'), isNotNull);
expect(box.get('name'), 'hive');
});
});
});
}
| bloc/packages/hydrated_bloc/test/hydrated_storage_test.dart/0 | {'file_path': 'bloc/packages/hydrated_bloc/test/hydrated_storage_test.dart', 'repo_id': 'bloc', 'token_count': 3077} |
import 'package:bloc/bloc.dart';
class MyBlocDelegate extends BlocDelegate {
@override
void onEvent(Bloc bloc, Object event) {
super.onEvent(bloc, event);
print('onEvent ${bloc.runtimeType}, $event');
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print('onTransition ${bloc.runtimeType}, $transition');
}
@override
void onError(Bloc bloc, Object error, StackTrace stacktrace) {
super.onError(bloc, error, stacktrace);
print('onError ${bloc.runtimeType}, $error, $stacktrace');
}
}
| bloc_library_basics_and_beyond/example/my_bloc_delegate.dart/0 | {'file_path': 'bloc_library_basics_and_beyond/example/my_bloc_delegate.dart', 'repo_id': 'bloc_library_basics_and_beyond', 'token_count': 209} |
part of 'filtered_todos_bloc.dart';
class FilteredTodosState extends Equatable {
const FilteredTodosState({
this.todos = const <Todo>[],
this.filteredTodos = const <Todo>[],
this.filter = VisibilityFilter.all,
});
final List<Todo> todos;
final List<Todo> filteredTodos;
final VisibilityFilter filter;
@override
List<Object> get props => [todos, filteredTodos, filter];
@override
bool get stringify => true;
}
| bloc_todos/lib/filtered_todos/bloc/filtered_todos_state.dart/0 | {'file_path': 'bloc_todos/lib/filtered_todos/bloc/filtered_todos_state.dart', 'repo_id': 'bloc_todos', 'token_count': 165} |
import 'package:bloc_todos/app/app.dart';
import 'package:bloc_todos/todos_bloc_delegate.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:todos_repository_simple/todos_repository_simple.dart';
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
BlocSupervisor.delegate = TodosBlocDelegate(
await HydratedBlocStorage.getInstance(),
);
const todosRepository = TodosRepositoryFlutter(
fileStorage: FileStorage(
'__flutter_bloc_app__',
getApplicationDocumentsDirectory,
),
);
runApp(const TodosApp(todosRepository: todosRepository));
}
| bloc_todos/lib/main.dart/0 | {'file_path': 'bloc_todos/lib/main.dart', 'repo_id': 'bloc_todos', 'token_count': 287} |
export 'bloc/todo_bloc.dart';
export 'todo_item.dart';
| bloc_todos/lib/todos/todo/todo.dart/0 | {'file_path': 'bloc_todos/lib/todos/todo/todo.dart', 'repo_id': 'bloc_todos', 'token_count': 26} |
import 'dart:ui';
import 'spritesheet.dart';
import 'player.dart';
import '../../main.dart';
import 'package:flame/sprite.dart';
enum Hat {
RIDER,
WIZARD,
GENTLEMAN,
COP,
KING,
COWBOY,
BASEBALL_CAP,
SOMBRERO,
ASTRONAUT,
KNIGHT,
SPARTAN,
SANTA,
JESTER,
WANDERER,
COMPOSER,
DIVER,
OLD_DIVER,
CONSTRUCTION_WORKER,
GRADUATE,
CHEF,
PIRATE_CAPTAIN,
ASSASSIN,
LEPRECHAUN,
FRANK,
PHARAOH,
VIKING,
DRINKING_HAT,
ARCHER,
FISH_HAT,
ROBIN_HOOD,
GNOME,
AFRO,
SAMURAI,
FIGHTER_PILOT,
SHIP_CAPTAIN,
}
class HatSprite {
SpriteSheet _spriteSheet;
Hat _hat;
HatSprite(this._hat, { Image image }) {
_spriteSheet = SpriteSheet(
image: image,
textureWidth: 48,
textureHeight: 32,
rows: 7,
columns: 5
);
}
void render(Canvas canvas, double x, double y, bool isGrowed, bool isShrunk) {
final delta = (isGrowed ? Player.GROW_RATE : isShrunk ? Player.SHRUNK_RATE : 1.0);
hatSprite.renderRect(
canvas,
Rect.fromLTWH(
x - 50 * delta,
y - 50 * delta,
150 * delta,
100 * delta
)
);
}
Sprite get rider => _spriteSheet.getSprite(0, 0);
Sprite get wizard => _spriteSheet.getSprite(1, 0);
Sprite get gentleman => _spriteSheet.getSprite(2, 0);
Sprite get cop => _spriteSheet.getSprite(3, 0);
Sprite get king => _spriteSheet.getSprite(4, 0);
Sprite get cowboy => _spriteSheet.getSprite(5, 0);
Sprite get baseballCap => _spriteSheet.getSprite(6, 0);
Sprite get sombrero => _spriteSheet.getSprite(0, 1);
Sprite get astronaut => _spriteSheet.getSprite(1, 1);
Sprite get knight => _spriteSheet.getSprite(2, 1);
Sprite get spartan => _spriteSheet.getSprite(3, 1);
Sprite get santa => _spriteSheet.getSprite(4, 1);
Sprite get jester => _spriteSheet.getSprite(5, 1);
Sprite get wanderer => _spriteSheet.getSprite(6, 1);
Sprite get composer => _spriteSheet.getSprite(0, 2);
Sprite get diver => _spriteSheet.getSprite(1, 2);
Sprite get oldDiver => _spriteSheet.getSprite(2, 2);
Sprite get constructionWorker => _spriteSheet.getSprite(3, 2);
Sprite get graduate => _spriteSheet.getSprite(4, 2);
Sprite get chef => _spriteSheet.getSprite(5, 2);
Sprite get pirateCaptain => _spriteSheet.getSprite(6, 2);
Sprite get assassin => _spriteSheet.getSprite(0, 3);
Sprite get leprechaun => _spriteSheet.getSprite(1, 3);
Sprite get frank => _spriteSheet.getSprite(2, 3);
Sprite get pharaoh => _spriteSheet.getSprite(3, 3);
Sprite get viking => _spriteSheet.getSprite(4, 3);
Sprite get drinkingHat => _spriteSheet.getSprite(5, 3);
Sprite get archer => _spriteSheet.getSprite(6, 3);
Sprite get fishHat => _spriteSheet.getSprite(0, 4);
Sprite get robinHood => _spriteSheet.getSprite(1, 4);
Sprite get gnome => _spriteSheet.getSprite(2, 4);
Sprite get afro => _spriteSheet.getSprite(3, 4);
Sprite get samurai => _spriteSheet.getSprite(4, 4);
Sprite get fighterPilot => _spriteSheet.getSprite(5, 4);
Sprite get shipCaptain => _spriteSheet.getSprite(6, 4);
String get label {
switch(_hat) {
case Hat.RIDER: {
return "Rider";
}
case Hat.WIZARD: {
return "Wizard";
}
case Hat.GENTLEMAN: {
return "Gentleman";
}
case Hat.COP: {
return "Cop";
}
case Hat.KING: {
return "King";
}
case Hat.COWBOY: {
return "Cowboy";
}
case Hat.BASEBALL_CAP: {
return "Baseball Cap";
}
case Hat.SOMBRERO: {
return "Sombrero";
}
case Hat.ASTRONAUT: {
return "Astronaut";
}
case Hat.KNIGHT: {
return "Knight";
}
case Hat.SPARTAN: {
return "Spartan";
}
case Hat.SANTA: {
return "Santa";
}
case Hat.JESTER: {
return "Jester";
}
case Hat.WANDERER: {
return "Wanderer";
}
case Hat.COMPOSER: {
return "Composer";
}
case Hat.DIVER: {
return "Diver";
}
case Hat.OLD_DIVER: {
return "Old Diver";
}
case Hat.CONSTRUCTION_WORKER: {
return "Worker";
}
case Hat.GRADUATE: {
return "Graduate";
}
case Hat.CHEF: {
return "Chef";
}
case Hat.PIRATE_CAPTAIN: {
return "Pirate Captain";
}
case Hat.ASSASSIN: {
return "Assassin";
}
case Hat.LEPRECHAUN: {
return "Leprechaun";
}
case Hat.FRANK: {
return "Frank";
}
case Hat.PHARAOH: {
return "Pharaoh";
}
case Hat.VIKING: {
return "Viking";
}
case Hat.DRINKING_HAT: {
return "Drinking Hat";
}
case Hat.ARCHER: {
return "Archer";
}
case Hat.FISH_HAT: {
return "Fish Hat";
}
case Hat.ROBIN_HOOD: {
return "Robin Hood";
}
case Hat.GNOME: {
return "Gnome";
}
case Hat.AFRO: {
return "Afro";
}
case Hat.SAMURAI: {
return "Samurai";
}
case Hat.FIGHTER_PILOT: {
return "Fighter Pilot";
}
case Hat.SHIP_CAPTAIN: {
return "Ship Captain";
}
}
}
Sprite get hatSprite {
switch(_hat) {
case Hat.RIDER: {
return rider;
}
case Hat.WIZARD: {
return wizard;
}
case Hat.GENTLEMAN: {
return gentleman;
}
case Hat.COP: {
return cop;
}
case Hat.KING: {
return king;
}
case Hat.COWBOY: {
return cowboy;
}
case Hat.BASEBALL_CAP: {
return baseballCap;
}
case Hat.SOMBRERO: {
return sombrero;
}
case Hat.ASTRONAUT: {
return astronaut;
}
case Hat.KNIGHT: {
return knight;
}
case Hat.SPARTAN: {
return spartan;
}
case Hat.SANTA: {
return santa;
}
case Hat.JESTER: {
return jester;
}
case Hat.WANDERER: {
return wanderer;
}
case Hat.COMPOSER: {
return composer;
}
case Hat.DIVER: {
return diver;
}
case Hat.OLD_DIVER: {
return oldDiver;
}
case Hat.CONSTRUCTION_WORKER: {
return constructionWorker;
}
case Hat.GRADUATE: {
return graduate;
}
case Hat.CHEF: {
return chef;
}
case Hat.PIRATE_CAPTAIN: {
return pirateCaptain;
}
case Hat.ASSASSIN: {
return assassin;
}
case Hat.LEPRECHAUN: {
return leprechaun;
}
case Hat.FRANK: {
return frank;
}
case Hat.PHARAOH: {
return pharaoh;
}
case Hat.VIKING: {
return viking;
}
case Hat.DRINKING_HAT: {
return drinkingHat;
}
case Hat.ARCHER: {
return archer;
}
case Hat.FISH_HAT: {
return fishHat;
}
case Hat.ROBIN_HOOD: {
return robinHood;
}
case Hat.GNOME: {
return gnome;
}
case Hat.AFRO: {
return afro;
}
case Hat.SAMURAI: {
return samurai;
}
case Hat.FIGHTER_PILOT: {
return fighterPilot;
}
case Hat.SHIP_CAPTAIN: {
return shipCaptain;
}
}
}
}
| bob_box/game/lib/screens/game/hats.dart/0 | {'file_path': 'bob_box/game/lib/screens/game/hats.dart', 'repo_id': 'bob_box', 'token_count': 3760} |
import "package:flutter/material.dart";
import "package:url_launcher/url_launcher.dart";
import "label.dart";
class Link extends StatelessWidget {
final String link;
Link({ this.link });
Widget build(BuildContext context) {
return GestureDetector(
child: Label(label: link, fontColor: const Color(0xFF55a894)),
onTap: () async {
if (await canLaunch(link)) {
await launch(link);
}
}
);
}
}
| bob_box/game/lib/ui/link.dart/0 | {'file_path': 'bob_box/game/lib/ui/link.dart', 'repo_id': 'bob_box', 'token_count': 195} |
// ignore_for_file: only_throw_errors
import 'package:boundary/boundary.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockFlutterError extends Mock {
void call(FlutterErrorDetails details);
}
class MockErrorBuilder extends Mock {
Widget call(FlutterErrorDetails details);
}
VoidCallback mockErrorHandlers({
FlutterExceptionHandler onError,
ErrorWidgetBuilder errorBuilder,
}) {
final o = FlutterError.onError;
final e = ErrorWidget.builder;
FlutterError.onError = onError;
ErrorWidget.builder = errorBuilder;
return () {
FlutterError.onError = o;
ErrorWidget.builder = e;
};
}
void main() {
testWidgets("fallback isn't called if child succeeds", (tester) async {
final key = GlobalKey();
final builder = BuilderMock();
await tester.pumpWidget(Boundary(
key: key,
fallbackBuilder: builder,
child: const Text('foo', textDirection: TextDirection.ltr),
));
expect(find.text('foo'), findsOneWidget);
expect(key.currentContext, isNotNull);
verifyZeroInteractions(builder);
});
testWidgets('root exception', (tester) async {
final builder = BuilderMock();
await tester.pumpWidget(
Boundary(
fallbackBuilder: (c, dynamic e) {
builder(c, e);
return Text(e.toString(), textDirection: TextDirection.ltr);
},
child: Builder(builder: (context) {
return Defer(42);
}),
),
);
expect(find.text('42'), findsOneWidget);
verify(builder(argThat(isNotNull), 42)).called(1);
verifyNoMoreInteractions(builder);
});
testWidgets('nested exception', (tester) async {
final builder = BuilderMock();
await tester.pumpWidget(
Boundary(
fallbackBuilder: (c, dynamic e) {
builder(c, e);
return Text(e.toString(), textDirection: TextDirection.ltr);
},
child: Container(
child: Builder(builder: (context) {
return Defer(42);
}),
),
),
);
expect(find.text('42'), findsOneWidget);
verify(builder(argThat(isNotNull), 42));
verifyNoMoreInteractions(builder);
});
testWidgets('late exception', (tester) async {
final notifier = ValueNotifier(0);
final builder = BuilderMock();
await tester.pumpWidget(
Boundary(
fallbackBuilder: (c, dynamic e) {
builder(c, e);
return Text(e.toString(), textDirection: TextDirection.ltr);
},
child: ValueListenableBuilder<int>(
valueListenable: notifier,
builder: (_, value, __) {
if (value == 1) return Defer(42);
return Text(value.toString(), textDirection: TextDirection.ltr);
},
),
),
);
expect(find.text('0'), findsOneWidget);
verifyZeroInteractions(builder);
notifier.value++;
await tester.pump();
verify(builder(argThat(isNotNull), 42)).called(1);
verifyNoMoreInteractions(builder);
expect(find.text('42'), findsOneWidget);
});
testWidgets('child rebuilding after an error stops showing fallback',
(tester) async {
final notifier = ValueNotifier(0);
final builder = BuilderMock();
await tester.pumpWidget(
Boundary(
fallbackBuilder: (c, dynamic e) {
builder(c, e);
return Text(e.toString(), textDirection: TextDirection.ltr);
},
child: ValueListenableBuilder<int>(
valueListenable: notifier,
builder: (_, value, __) {
if (value == 0) return Defer(42);
return Text(value.toString(), textDirection: TextDirection.ltr);
},
),
),
);
clearInteractions(builder);
notifier.value++;
await tester.pump();
verifyNoMoreInteractions(builder);
expect(find.text('1'), findsOneWidget);
});
testWidgets(
'both rebuilding the boundary and fixing the error simultaneously removes the fallback',
(tester) async {
final builder = BuilderMock();
await tester.pumpWidget(Boundary(
fallbackBuilder: (_, dynamic __) {
return const Text('fallback', textDirection: TextDirection.ltr);
},
child: Builder(
builder: (context) => Defer(42),
),
));
await tester.pumpWidget(Boundary(
fallbackBuilder: (_, dynamic __) {
builder(_, __);
return const Text('fallback', textDirection: TextDirection.ltr);
},
child: Builder(
builder: (context) =>
const Text('42', textDirection: TextDirection.ltr),
),
));
verifyZeroInteractions(builder);
expect(find.text('fallback'), findsNothing);
expect(find.text('42'), findsOneWidget);
});
testWidgets(
'fallbackBuilder can throw to propagate the exception to other boundaries',
(tester) async {
final builder = BuilderMock();
final builder2 = BuilderMock();
await tester.pumpWidget(Boundary(
fallbackBuilder: (c, dynamic err) {
builder2(c, err);
return Container();
},
child: Builder(
builder: (context) {
return Boundary(
fallbackBuilder: (c, dynamic err) {
builder(c, err);
return Defer(err);
},
child: Builder(builder: (_) => Defer(42)),
);
},
),
));
verifyInOrder([
builder(any, 42),
builder2(any, 42),
]);
verifyNoMoreInteractions(builder);
verifyNoMoreInteractions(builder2);
});
testWidgets('late propagation', (tester) async {
final builder = BuilderMock();
final builder2 = BuilderMock();
final notifier = ValueNotifier(0);
await tester.pumpWidget(Boundary(
fallbackBuilder: (c, dynamic err) {
builder2(c, err);
return const Text('fallback', textDirection: TextDirection.ltr);
},
child: Boundary(
fallbackBuilder: (c, dynamic err) {
builder(c, err);
return Defer(err);
},
child: ValueListenableBuilder<int>(
valueListenable: notifier,
builder: (_, value, __) {
if (value == 1) return Defer(42);
return Text(value.toString(), textDirection: TextDirection.ltr);
},
),
),
));
verifyZeroInteractions(builder);
verifyZeroInteractions(builder2);
expect(find.text('0'), findsOneWidget);
notifier.value++;
await tester.pump();
expect(find.text('0'), findsNothing);
expect(find.text('fallback'), findsOneWidget);
verifyInOrder([
builder(any, 42),
builder2(any, 42),
]);
verifyNoMoreInteractions(builder);
verifyNoMoreInteractions(builder2);
notifier.value++;
await tester.pump();
verifyNoMoreInteractions(builder);
verifyNoMoreInteractions(builder2);
expect(find.text('2'), findsOneWidget);
});
testWidgets(
'propagated error when rebuild successfuly correctly hides fallback widget',
(tester) async {
final builder = BuilderMock();
final builder2 = BuilderMock();
final notifier = ValueNotifier(0);
await tester.pumpWidget(Boundary(
fallbackBuilder: (c, dynamic err) {
builder2(c, err);
return const Text('fallback', textDirection: TextDirection.ltr);
},
child: Boundary(
fallbackBuilder: (c, dynamic err) {
builder(c, err);
return Defer(err);
},
child: ValueListenableBuilder<int>(
valueListenable: notifier,
builder: (_, value, __) {
if (value == 0) return Defer(42);
return Text(value.toString(), textDirection: TextDirection.ltr);
},
),
),
));
clearInteractions(builder);
clearInteractions(builder2);
expect(find.text('fallback'), findsOneWidget);
notifier.value++;
await tester.pump();
verifyNoMoreInteractions(builder);
verifyNoMoreInteractions(builder2);
expect(find.text('1'), findsOneWidget);
});
testWidgets(
"fallback don't lose its state when trying to rebuild child unsuccessfuly",
(tester) async {
var initCount = 0;
await tester.pumpWidget(
Boundary(
fallbackBuilder: (_, dynamic __) =>
MyStateful(didInitState: () => initCount++),
child: Builder(builder: (_) => Defer(42)),
),
);
await tester.pumpWidget(
Boundary(
fallbackBuilder: (_, dynamic __) =>
MyStateful(didInitState: () => initCount++),
child: Builder(builder: (_) => Defer(42)),
),
);
expect(initCount, equals(1));
});
testWidgets('Defer without a Boundary in its ancestors report an error',
(tester) async {
await tester.pumpWidget(Defer(42));
// ignore: omit_local_variable_types
final dynamic exception = tester.takeException();
expect(exception, isInstanceOf<BoundaryNotFoundError>());
expect(exception.toString(), equals('''
Error: No Boundary<int> found.
'''));
});
testWidgets("child doesn't rebuild if didn't change and no error",
(tester) async {
var buildCount = 0;
final child = Builder(builder: (_) {
buildCount++;
return Container();
});
await tester.pumpWidget(
Boundary(
fallbackBuilder: (_, dynamic __) => null,
child: child,
),
);
await tester.pumpWidget(
Boundary(
fallbackBuilder: (_, dynamic __) => null,
child: child,
),
);
expect(buildCount, equals(1));
});
testWidgets('child is provided its constraints unmodified', (tester) async {
final expectedConstraints = const BoxConstraints(
minWidth: 50,
maxWidth: 100,
minHeight: 25,
maxHeight: 60,
);
BoxConstraints actualConstraints;
await tester.pumpWidget(
// UnconstrainedBox to ignore tester's constraints
UnconstrainedBox(
child: ConstrainedBox(
constraints: expectedConstraints,
child: Boundary(
fallbackBuilder: (_, dynamic __) => null,
child: LayoutBuilder(builder: (_, constraints) {
actualConstraints = constraints;
return const SizedBox();
}),
),
),
),
);
expect(actualConstraints, equals(expectedConstraints));
});
}
class BuilderMock extends Mock {
Widget call(BuildContext context, dynamic error);
}
class MyStateful extends StatefulWidget {
const MyStateful({Key key, this.didInitState}) : super(key: key);
final VoidCallback didInitState;
@override
_MyStatefulState createState() => _MyStatefulState();
}
class _MyStatefulState extends State<MyStateful> {
@override
void initState() {
super.initState();
widget.didInitState?.call();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
| boundary/test/boundary_test.dart/0 | {'file_path': 'boundary/test/boundary_test.dart', 'repo_id': 'boundary', 'token_count': 4490} |
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
linter:
rules:
- slash_for_doc_comments | box2d.dart/analysis_options.yaml/0 | {'file_path': 'box2d.dart/analysis_options.yaml', 'repo_id': 'box2d.dart', 'token_count': 48} |
/// *****************************************************************************
/// Copyright (c) 2015, Daniel Murphy, Google
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
/// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
/// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// *****************************************************************************
library racer;
import 'dart:html' hide Body;
import 'dart:math';
import 'package:box2d_flame/box2d.dart';
import 'package:box2d_flame/src/math_utils.dart' as MathUtils;
import 'demo.dart';
part 'racer/car.dart';
part 'racer/control_state.dart';
part 'racer/ground_area.dart';
part 'racer/tire.dart';
class Racer extends Demo implements ContactListener {
static void main() {
final racer = new Racer();
racer.initialize();
racer.initializeAnimation();
document.body.nodes
.add(new Element.html("<p>Use the arrow keys to drive the car.</p>"));
racer.runAnimation();
}
Racer() : super("Racer", new Vector2.zero(), 2.5);
void initialize() {
_createGround();
_createBoundary();
_car = new Car(world);
_controlState = 0;
// Bind to keyboard events.
document.onKeyDown.listen(_handleKeyDown);
document.onKeyUp.listen(_handleKeyUp);
// Add ourselves as a collision listener.
world.setContactListener(this);
}
void step(num time) {
_car.update(time - _lastTime, _controlState);
_lastTime = time;
super.step(time);
}
// ContactListener overrides.
void beginContact(Contact contact) {
_handleContact(contact, true);
}
void endContact(Contact contact) {
_handleContact(contact, false);
}
void preSolve(Contact contact, Manifold oldManifold) {}
void postSolve(Contact contact, ContactImpulse impulse) {}
double radians(double deg) => deg * (pi / 180.0);
void _createGround() {
BodyDef def = new BodyDef();
_groundBody = world.createBody(def);
_groundBody.userData = "Ground";
PolygonShape shape = new PolygonShape();
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.isSensor = true;
fixtureDef.userData = new GroundArea(0.001, false);
shape.setAsBox(27.0, 21.0, new Vector2(-30.0, 30.0), radians(20.0));
_groundBody.createFixtureFromFixtureDef(fixtureDef);
fixtureDef.userData = new GroundArea(0.2, false);
shape.setAsBox(27.0, 15.0, new Vector2(20.0, 40.0), radians(-40.0));
_groundBody.createFixtureFromFixtureDef(fixtureDef);
}
void _createBoundary() {
BodyDef def = new BodyDef();
Body boundaryBody = world.createBody(def);
boundaryBody.userData = "Boundary";
PolygonShape shape = new PolygonShape();
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
final double boundaryX = 150.0;
final double boundaryY = 100.0;
shape.setAsEdge(new Vector2(-boundaryX, -boundaryY),
new Vector2(boundaryX, -boundaryY));
boundaryBody.createFixtureFromFixtureDef(fixtureDef);
shape.setAsEdge(
new Vector2(boundaryX, -boundaryY), new Vector2(boundaryX, boundaryY));
boundaryBody.createFixtureFromFixtureDef(fixtureDef);
shape.setAsEdge(
new Vector2(boundaryX, boundaryY), new Vector2(-boundaryX, boundaryY));
boundaryBody.createFixtureFromFixtureDef(fixtureDef);
shape.setAsEdge(new Vector2(-boundaryX, boundaryY),
new Vector2(-boundaryX, -boundaryY));
boundaryBody.createFixtureFromFixtureDef(fixtureDef);
}
void _handleKeyDown(KeyboardEvent event) {
switch (event.keyCode) {
case 37:
_controlState |= ControlState.LEFT;
break;
case 38:
_controlState |= ControlState.UP;
break;
case 39:
_controlState |= ControlState.RIGHT;
break;
case 40:
_controlState |= ControlState.DOWN;
break;
}
}
void _handleKeyUp(KeyboardEvent event) {
switch (event.keyCode) {
case 37:
_controlState &= ~ControlState.LEFT;
break;
case 38:
_controlState &= ~ControlState.UP;
break;
case 39:
_controlState &= ~ControlState.RIGHT;
break;
case 40:
_controlState &= ~ControlState.DOWN;
break;
}
}
// TODO: collision filtering.
// Tire with Boundary
// Tire with GroundArea
void _handleContact(Contact contact, bool began) {
final Object fudA = contact.fixtureA.userData;
final Object fudB = contact.fixtureB.userData;
// Check for ground area collision.
// TODO: named parameters instead of swapping order?
if (fudA is Tire && fudB is GroundArea) {
_tireVsGroundArea(fudA, fudB, began);
} else if (fudA is GroundArea && fudB is Tire) {
_tireVsGroundArea(fudB, fudA, began);
}
}
void _tireVsGroundArea(Tire tire, GroundArea groundArea, bool began) {
if (began) {
tire.addGroundArea(groundArea);
} else {
tire.removeGroundArea(groundArea);
}
}
int _controlState;
Body _groundBody;
Car _car;
num _lastTime = 0;
}
void main() {
Racer.main();
}
| box2d.dart/example/racer.dart/0 | {'file_path': 'box2d.dart/example/racer.dart', 'repo_id': 'box2d.dart', 'token_count': 2238} |
/// *****************************************************************************
/// Copyright (c) 2015, Daniel Murphy, Google
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modification,
/// are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
/// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
/// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// *****************************************************************************
part of box2d;
/// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates.
class _SimplexVertex {
final Vector2 wA = new Vector2.zero(); // support point in shapeA
final Vector2 wB = new Vector2.zero(); // support point in shapeB
final Vector2 w = new Vector2.zero(); // wB - wA
double a = 0.0; // barycentric coordinate for closest point
int indexA = 0; // wA index
int indexB = 0; // wB index
void set(_SimplexVertex sv) {
wA.setFrom(sv.wA);
wB.setFrom(sv.wB);
w.setFrom(sv.w);
a = sv.a;
indexA = sv.indexA;
indexB = sv.indexB;
}
}
class SimplexCache {
/// length or area
double metric = 0.0;
int count = 0;
/// vertices on shape A
final List<int> indexA = BufferUtils.allocClearIntList(3);
/// vertices on shape B
final List<int> indexB = BufferUtils.allocClearIntList(3);
SimplexCache() {
indexA[0] = Settings.INTEGER_MAX_VALUE;
indexA[1] = Settings.INTEGER_MAX_VALUE;
indexA[2] = Settings.INTEGER_MAX_VALUE;
indexB[0] = Settings.INTEGER_MAX_VALUE;
indexB[1] = Settings.INTEGER_MAX_VALUE;
indexB[2] = Settings.INTEGER_MAX_VALUE;
}
void set(SimplexCache sc) {
BufferUtils.arraycopy(sc.indexA, 0, indexA, 0, indexA.length);
BufferUtils.arraycopy(sc.indexB, 0, indexB, 0, indexB.length);
metric = sc.metric;
count = sc.count;
}
}
class _Simplex {
final _SimplexVertex v1 = new _SimplexVertex();
final _SimplexVertex v2 = new _SimplexVertex();
final _SimplexVertex v3 = new _SimplexVertex();
final List<_SimplexVertex> vertices = new List<_SimplexVertex>(3);
int count = 0;
_Simplex() {
vertices[0] = v1;
vertices[1] = v2;
vertices[2] = v3;
}
void readCache(SimplexCache cache, DistanceProxy proxyA, Transform transformA,
DistanceProxy proxyB, Transform transformB) {
assert(cache.count <= 3);
// Copy data from cache.
count = cache.count;
for (int i = 0; i < count; ++i) {
_SimplexVertex v = vertices[i];
v.indexA = cache.indexA[i];
v.indexB = cache.indexB[i];
Vector2 wALocal = proxyA.getVertex(v.indexA);
Vector2 wBLocal = proxyB.getVertex(v.indexB);
Transform.mulToOutUnsafeVec2(transformA, wALocal, v.wA);
Transform.mulToOutUnsafeVec2(transformB, wBLocal, v.wB);
v.w
..setFrom(v.wB)
..sub(v.wA);
v.a = 0.0;
}
// Compute the new simplex metric, if it is substantially different than
// old metric then flush the simplex.
if (count > 1) {
double metric1 = cache.metric;
double metric2 = getMetric();
if (metric2 < 0.5 * metric1 ||
2.0 * metric1 < metric2 ||
metric2 < Settings.EPSILON) {
// Reset the simplex.
count = 0;
}
}
// If the cache is empty or invalid ...
if (count == 0) {
_SimplexVertex v = vertices[0];
v.indexA = 0;
v.indexB = 0;
Vector2 wALocal = proxyA.getVertex(0);
Vector2 wBLocal = proxyB.getVertex(0);
Transform.mulToOutUnsafeVec2(transformA, wALocal, v.wA);
Transform.mulToOutUnsafeVec2(transformB, wBLocal, v.wB);
v.w
..setFrom(v.wB)
..sub(v.wA);
count = 1;
}
}
void writeCache(SimplexCache cache) {
cache.metric = getMetric();
cache.count = count;
for (int i = 0; i < count; ++i) {
cache.indexA[i] = (vertices[i].indexA).toInt();
cache.indexB[i] = (vertices[i].indexB).toInt();
}
}
final Vector2 _e12 = new Vector2.zero();
void getSearchDirection(final Vector2 out) {
switch (count) {
case 1:
out
..setFrom(v1.w)
..negate();
return;
case 2:
_e12
..setFrom(v2.w)
..sub(v1.w);
// use out for a temp variable real quick
out
..setFrom(v1.w)
..negate();
double sgn = _e12.cross(out);
if (sgn > 0.0) {
// Origin is left of e12.
_e12.scaleOrthogonalInto(1.0, out);
} else {
// Origin is right of e12.
_e12.scaleOrthogonalInto(-1.0, out);
}
return;
default:
assert(false);
out.setZero();
return;
}
}
// djm pooled
final Vector2 _case2 = new Vector2.zero();
final Vector2 _case22 = new Vector2.zero();
/// This returns pooled objects. don't keep or modify them
void getClosestPoint(final Vector2 out) {
switch (count) {
case 0:
assert(false);
out.setZero();
return;
case 1:
out.setFrom(v1.w);
return;
case 2:
_case22
..setFrom(v2.w)
..scale(v2.a);
_case2
..setFrom(v1.w)
..scale(v1.a)
..add(_case22);
out.setFrom(_case2);
return;
case 3:
out.setZero();
return;
default:
assert(false);
out.setZero();
return;
}
}
// djm pooled, and from above
final Vector2 _case3 = new Vector2.zero();
final Vector2 _case33 = new Vector2.zero();
void getWitnessPoints(Vector2 pA, Vector2 pB) {
switch (count) {
case 0:
assert(false);
break;
case 1:
pA.setFrom(v1.wA);
pB.setFrom(v1.wB);
break;
case 2:
_case2
..setFrom(v1.wA)
..scale(v1.a);
pA
..setFrom(v2.wA)
..scale(v2.a)
..add(_case2);
// v1.a * v1.wA + v2.a * v2.wA;
// *pB = v1.a * v1.wB + v2.a * v2.wB;
_case2
..setFrom(v1.wB)
..scale(v1.a);
pB
..setFrom(v2.wB)
..scale(v2.a)
..add(_case2);
break;
case 3:
pA
..setFrom(v1.wA)
..scale(v1.a);
_case3
..setFrom(v2.wA)
..scale(v2.a);
_case33
..setFrom(v3.wA)
..scale(v3.a);
pA..add(_case3)..add(_case33);
pB.setFrom(pA);
// *pA = v1.a * v1.wA + v2.a * v2.wA + v3.a * v3.wA;
// *pB = *pA;
break;
default:
assert(false);
break;
}
}
// djm pooled, from above
double getMetric() {
switch (count) {
case 0:
assert(false);
return 0.0;
case 1:
return 0.0;
case 2:
return MathUtils.distance(v1.w, v2.w);
case 3:
_case3
..setFrom(v2.w)
..sub(v1.w);
_case33
..setFrom(v3.w)
..sub(v1.w);
// return Vec2.cross(v2.w - v1.w, v3.w - v1.w);
return _case3.cross(_case33);
default:
assert(false);
return 0.0;
}
}
// djm pooled from above
/// Solve a line segment using barycentric coordinates.
void solve2() {
// Solve a line segment using barycentric coordinates.
//
// p = a1 * w1 + a2 * w2
// a1 + a2 = 1
//
// The vector from the origin to the closest point on the line is
// perpendicular to the line.
// e12 = w2 - w1
// dot(p, e) = 0
// a1 * dot(w1, e) + a2 * dot(w2, e) = 0
//
// 2-by-2 linear system
// [1 1 ][a1] = [1]
// [w1.e12 w2.e12][a2] = [0]
//
// Define
// d12_1 = dot(w2, e12)
// d12_2 = -dot(w1, e12)
// d12 = d12_1 + d12_2
//
// Solution
// a1 = d12_1 / d12
// a2 = d12_2 / d12
final Vector2 w1 = v1.w;
final Vector2 w2 = v2.w;
_e12
..setFrom(w2)
..sub(w1);
// w1 region
double d12_2 = -w1.dot(_e12);
if (d12_2 <= 0.0) {
// a2 <= 0, so we clamp it to 0
v1.a = 1.0;
count = 1;
return;
}
// w2 region
double d12_1 = w2.dot(_e12);
if (d12_1 <= 0.0) {
// a1 <= 0, so we clamp it to 0
v2.a = 1.0;
count = 1;
v1.set(v2);
return;
}
// Must be in e12 region.
double inv_d12 = 1.0 / (d12_1 + d12_2);
v1.a = d12_1 * inv_d12;
v2.a = d12_2 * inv_d12;
count = 2;
}
// djm pooled, and from above
final Vector2 _e13 = new Vector2.zero();
final Vector2 _e23 = new Vector2.zero();
final Vector2 _w1 = new Vector2.zero();
final Vector2 _w2 = new Vector2.zero();
final Vector2 _w3 = new Vector2.zero();
/// Solve a line segment using barycentric coordinates.<br/>
/// Possible regions:<br/>
/// - points[2]<br/>
/// - edge points[0]-points[2]<br/>
/// - edge points[1]-points[2]<br/>
/// - inside the triangle
void solve3() {
_w1.setFrom(v1.w);
_w2.setFrom(v2.w);
_w3.setFrom(v3.w);
// Edge12
// [1 1 ][a1] = [1]
// [w1.e12 w2.e12][a2] = [0]
// a3 = 0
_e12
..setFrom(_w2)
..sub(_w1);
double w1e12 = _w1.dot(_e12);
double w2e12 = _w2.dot(_e12);
double d12_1 = w2e12;
double d12_2 = -w1e12;
// Edge13
// [1 1 ][a1] = [1]
// [w1.e13 w3.e13][a3] = [0]
// a2 = 0
_e13
..setFrom(_w3)
..sub(_w1);
double w1e13 = _w1.dot(_e13);
double w3e13 = _w3.dot(_e13);
double d13_1 = w3e13;
double d13_2 = -w1e13;
// Edge23
// [1 1 ][a2] = [1]
// [w2.e23 w3.e23][a3] = [0]
// a1 = 0
_e23
..setFrom(_w3)
..sub(_w2);
double w2e23 = _w2.dot(_e23);
double w3e23 = _w3.dot(_e23);
double d23_1 = w3e23;
double d23_2 = -w2e23;
// Triangle123
double n123 = _e12.cross(_e13);
double d123_1 = n123 * _w2.cross(_w3);
double d123_2 = n123 * _w3.cross(_w1);
double d123_3 = n123 * _w1.cross(_w2);
// w1 region
if (d12_2 <= 0.0 && d13_2 <= 0.0) {
v1.a = 1.0;
count = 1;
return;
}
// e12
if (d12_1 > 0.0 && d12_2 > 0.0 && d123_3 <= 0.0) {
double inv_d12 = 1.0 / (d12_1 + d12_2);
v1.a = d12_1 * inv_d12;
v2.a = d12_2 * inv_d12;
count = 2;
return;
}
// e13
if (d13_1 > 0.0 && d13_2 > 0.0 && d123_2 <= 0.0) {
double inv_d13 = 1.0 / (d13_1 + d13_2);
v1.a = d13_1 * inv_d13;
v3.a = d13_2 * inv_d13;
count = 2;
v2.set(v3);
return;
}
// w2 region
if (d12_1 <= 0.0 && d23_2 <= 0.0) {
v2.a = 1.0;
count = 1;
v1.set(v2);
return;
}
// w3 region
if (d13_1 <= 0.0 && d23_1 <= 0.0) {
v3.a = 1.0;
count = 1;
v1.set(v3);
return;
}
// e23
if (d23_1 > 0.0 && d23_2 > 0.0 && d123_1 <= 0.0) {
double inv_d23 = 1.0 / (d23_1 + d23_2);
v2.a = d23_1 * inv_d23;
v3.a = d23_2 * inv_d23;
count = 2;
v1.set(v3);
return;
}
// Must be in triangle123
double inv_d123 = 1.0 / (d123_1 + d123_2 + d123_3);
v1.a = d123_1 * inv_d123;
v2.a = d123_2 * inv_d123;
v3.a = d123_3 * inv_d123;
count = 3;
}
} // Class _Simplex
class DistanceProxy {
final List<Vector2> vertices;
int _count;
double radius;
final List<Vector2> buffer;
DistanceProxy()
: vertices = new List<Vector2>(Settings.maxPolygonVertices),
buffer = new List<Vector2>(2) {
for (int i = 0; i < vertices.length; i++) {
vertices[i] = new Vector2.zero();
}
_count = 0;
radius = 0.0;
}
/// Initialize the proxy using the given shape. The shape must remain in scope while the proxy is
/// in use.
void set(final Shape shape, int index) {
switch (shape.shapeType) {
case ShapeType.CIRCLE:
final circle = shape as CircleShape;
vertices[0].setFrom(circle.p);
_count = 1;
radius = circle.radius;
break;
case ShapeType.POLYGON:
final poly = shape as PolygonShape;
_count = poly.count;
radius = poly.radius;
for (int i = 0; i < _count; i++) {
vertices[i].setFrom(poly.vertices[i]);
}
break;
case ShapeType.CHAIN:
final chain = shape as ChainShape;
assert(0 <= index && index < chain._count);
buffer[0] = chain._vertices[index];
if (index + 1 < chain._count) {
buffer[1] = chain._vertices[index + 1];
} else {
buffer[1] = chain._vertices[0];
}
vertices[0].setFrom(buffer[0]);
vertices[1].setFrom(buffer[1]);
_count = 2;
radius = chain.radius;
break;
case ShapeType.EDGE:
final edge = shape as EdgeShape;
vertices[0].setFrom(edge.vertex1);
vertices[1].setFrom(edge.vertex2);
_count = 2;
radius = edge.radius;
break;
default:
assert(false);
}
}
/// Get the supporting vertex index in the given direction.
int getSupport(final Vector2 d) {
int bestIndex = 0;
double bestValue = vertices[0].dot(d);
for (int i = 1; i < _count; i++) {
double value = vertices[i].dot(d);
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
}
/// Get the supporting vertex in the given direction.
Vector2 getSupportVertex(final Vector2 d) {
int bestIndex = 0;
double bestValue = vertices[0].dot(d);
for (int i = 1; i < _count; i++) {
double value = vertices[i].dot(d);
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return vertices[bestIndex];
}
/// Get the vertex count.
int getVertexCount() {
return _count;
}
/// Get a vertex by index. Used by Distance.
Vector2 getVertex(int index) {
assert(0 <= index && index < _count);
return vertices[index];
}
} // Class _DistanceProxy.
class Distance {
static const int MAX_ITERS = 20;
static int GJK_CALLS = 0;
static int GJK_ITERS = 0;
static int GJK_MAX_ITERS = 20;
final _Simplex _simplex = new _Simplex();
final List<int> _saveA = BufferUtils.allocClearIntList(3);
final List<int> _saveB = BufferUtils.allocClearIntList(3);
final Vector2 _closestPoint = new Vector2.zero();
final Vector2 _d = new Vector2.zero();
final Vector2 _temp = new Vector2.zero();
final Vector2 _normal = new Vector2.zero();
/// Compute the closest points between two shapes. Supports any combination of: CircleShape and
/// PolygonShape. The simplex cache is input/output. On the first call set SimplexCache.count to
/// zero.
void distance(final DistanceOutput output, final SimplexCache cache,
final DistanceInput input) {
GJK_CALLS++;
final DistanceProxy proxyA = input.proxyA;
final DistanceProxy proxyB = input.proxyB;
Transform transformA = input.transformA;
Transform transformB = input.transformB;
// Initialize the simplex.
_simplex.readCache(cache, proxyA, transformA, proxyB, transformB);
// Get simplex vertices as an array.
List<_SimplexVertex> vertices = _simplex.vertices;
// These store the vertices of the last simplex so that we
// can check for duplicates and prevent cycling.
// (pooled above)
int saveCount = 0;
_simplex.getClosestPoint(_closestPoint);
double distanceSqr1 = _closestPoint.length2;
double distanceSqr2 = distanceSqr1;
// Main iteration loop
int iter = 0;
while (iter < MAX_ITERS) {
// Copy simplex so we can identify duplicates.
saveCount = _simplex.count;
for (int i = 0; i < saveCount; i++) {
_saveA[i] = vertices[i].indexA;
_saveB[i] = vertices[i].indexB;
}
switch (_simplex.count) {
case 1:
break;
case 2:
_simplex.solve2();
break;
case 3:
_simplex.solve3();
break;
default:
assert(false);
}
// If we have 3 points, then the origin is in the corresponding triangle.
if (_simplex.count == 3) {
break;
}
// Compute closest point.
_simplex.getClosestPoint(_closestPoint);
distanceSqr2 = _closestPoint.length2;
// ensure progress
if (distanceSqr2 >= distanceSqr1) {
// break;
}
distanceSqr1 = distanceSqr2;
// get search direction;
_simplex.getSearchDirection(_d);
// Ensure the search direction is numerically fit.
if (_d.length2 < Settings.EPSILON * Settings.EPSILON) {
// The origin is probably contained by a line segment
// or triangle. Thus the shapes are overlapped.
// We can't return zero here even though there may be overlap.
// In case the simplex is a point, segment, or triangle it is difficult
// to determine if the origin is contained in the CSO or very close to it.
break;
}
/*
* SimplexVertex* vertex = vertices + simplex.count; vertex.indexA =
* proxyA.GetSupport(MulT(transformA.R, -d)); vertex.wA = Mul(transformA,
* proxyA.GetVertex(vertex.indexA)); Vec2 wBLocal; vertex.indexB =
* proxyB.GetSupport(MulT(transformB.R, d)); vertex.wB = Mul(transformB,
* proxyB.GetVertex(vertex.indexB)); vertex.w = vertex.wB - vertex.wA;
*/
// Compute a tentative new simplex vertex using support points.
_SimplexVertex vertex = vertices[_simplex.count];
Rot.mulTransUnsafeVec2(transformA.q, _d..negate(), _temp);
vertex.indexA = proxyA.getSupport(_temp);
Transform.mulToOutUnsafeVec2(
transformA, proxyA.getVertex(vertex.indexA), vertex.wA);
// Vec2 wBLocal;
Rot.mulTransUnsafeVec2(transformB.q, _d..negate(), _temp);
vertex.indexB = proxyB.getSupport(_temp);
Transform.mulToOutUnsafeVec2(
transformB, proxyB.getVertex(vertex.indexB), vertex.wB);
(vertex.w..setFrom(vertex.wB)).sub(vertex.wA);
// Iteration count is equated to the number of support point calls.
++iter;
++GJK_ITERS;
// Check for duplicate support points. This is the main termination criteria.
bool duplicate = false;
for (int i = 0; i < saveCount; ++i) {
if (vertex.indexA == _saveA[i] && vertex.indexB == _saveB[i]) {
duplicate = true;
break;
}
}
// If we found a duplicate support point we must exit to avoid cycling.
if (duplicate) {
break;
}
// New vertex is ok and needed.
++_simplex.count;
}
GJK_MAX_ITERS = Math.max(GJK_MAX_ITERS, iter);
// Prepare output.
_simplex.getWitnessPoints(output.pointA, output.pointB);
output.distance = MathUtils.distance(output.pointA, output.pointB);
output.iterations = iter;
// Cache the simplex.
_simplex.writeCache(cache);
// Apply radii if requested.
if (input.useRadii) {
double rA = proxyA.radius;
double rB = proxyB.radius;
if (output.distance > rA + rB && output.distance > Settings.EPSILON) {
// Shapes are still no overlapped.
// Move the witness points to the outer surface.
output.distance -= rA + rB;
_normal
..setFrom(output.pointB)
..sub(output.pointA);
_normal.normalize();
_temp
..setFrom(_normal)
..scale(rA);
output.pointA.add(_temp);
_temp
..setFrom(_normal)
..scale(rB);
output.pointB.sub(_temp);
} else {
// Shapes are overlapped when radii are considered.
// Move the witness points to the middle.
// Vec2 p = 0.5f * (output.pointA + output.pointB);
output.pointA
..add(output.pointB)
..scale(.5);
output.pointB.setFrom(output.pointA);
output.distance = 0.0;
}
}
}
}
| box2d.dart/lib/src/collision/distance.dart/0 | {'file_path': 'box2d.dart/lib/src/collision/distance.dart', 'repo_id': 'box2d.dart', 'token_count': 9731} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.