repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/expand_list.dart | import 'package:expand_widget/expand_widget.dart';
import 'package:flutter/material.dart';
/// Wrapper on [ExpandChild]. It expands a widget, and then it hides
/// the expanding arrow.
class ExpandList extends StatelessWidget {
final Widget child;
final String hint;
const ExpandList({
Key key,
@required this.child,
this.hint,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ExpandChild(
expandArrowStyle: ExpandArrowStyle.text,
hideArrowOnExpanded: true,
collapsedHint: hint,
child: child,
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/dialog_patreon.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:row_collection/row_collection.dart';
import '../../utils/index.dart';
/// List of past & current Patreon supporters.
/// Thanks to you all! :)
const List<String> _patreons = [
'John Stockbridge',
'Ahmed Al Hamada',
'Michael Christenson II',
'Malcolm',
'Pierangelo Pancera',
'Sam M',
'Tim van der Linde',
'David Morrow'
];
/// Dialog that appears every once in a while, with
/// the Patreon information from this app's lead developer.
Future<T> showPatreonDialog<T>(BuildContext context) {
return showRoundDialog(
context: context,
title: context.translate('about.patreon.title'),
children: [
RowLayout(
padding: EdgeInsets.symmetric(horizontal: 20),
children: <Widget>[
Text(
context.translate('about.patreon.body_dialog'),
textAlign: TextAlign.justify,
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
for (String patreon in _patreons)
Text(
patreon,
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
if (Theme.of(context).platform != TargetPlatform.iOS)
Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context, false),
child: Text(
context.translate('about.patreon.dismiss'),
style: Theme.of(context).textTheme.bodyText2.copyWith(
color: Theme.of(context).textTheme.caption.color,
),
),
),
OutlineButton(
highlightedBorderColor: Theme.of(context).accentColor,
borderSide: BorderSide(
color: Theme.of(context).textTheme.headline6.color,
),
onPressed: () {
Navigator.pop(context, true);
context.openUrl(Url.authorPatreon);
},
child: Text(
'PATREON',
style: Theme.of(context).textTheme.bodyText2,
),
),
],
),
)
],
),
],
);
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/profile_image.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
/// This widget helps by forcing a size to a cached image,
/// or anykind of widget, all around the app.
class ProfileImage extends StatelessWidget {
static const smallSize = 40.0, bigSize = 69.0;
final String url;
final num size;
final VoidCallback onTap;
const ProfileImage({
@required this.url,
@required this.size,
this.onTap,
});
/// Leading parameter of a [ListCell] widget.
factory ProfileImage.small(String url) {
return ProfileImage(url: url, size: smallSize);
}
/// Header of a [CardCell] widget.
factory ProfileImage.big(String url, {VoidCallback onTap}) {
return ProfileImage(url: url, size: bigSize, onTap: onTap);
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: InkWell(
onTap: onTap,
child: url != null
? CachedNetworkImage(
imageUrl: url,
fit: BoxFit.fitHeight,
)
: SvgPicture.asset(
'assets/icons/patch.svg',
colorBlendMode: BlendMode.srcATop,
color: Theme.of(context).brightness == Brightness.light
? Colors.black45
: Colors.black26,
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/launch_countdown.dart | import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:row_collection/row_collection.dart';
import '../../utils/translate.dart';
/// Stateful widget used to display a countdown to the next launch.
class LaunchCountdown extends StatefulWidget {
final DateTime launchDate;
const LaunchCountdown(this.launchDate);
@override
State createState() => _LaunchCountdownState();
}
class _LaunchCountdownState extends State<LaunchCountdown>
with TickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(
seconds: widget.launchDate.millisecondsSinceEpoch -
DateTime.now().millisecondsSinceEpoch,
),
);
_controller.forward(from: 0.0);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Countdown(
animation: StepTween(
begin: widget.launchDate.millisecondsSinceEpoch,
end: DateTime.now().millisecondsSinceEpoch,
).animate(_controller),
launchDate: widget.launchDate,
);
}
}
class Countdown extends AnimatedWidget {
final Animation<int> animation;
final DateTime launchDate;
const Countdown({
Key key,
this.animation,
this.launchDate,
}) : super(key: key, listenable: animation);
@override
Widget build(BuildContext context) {
final Duration _launchDateDiff = launchDate.difference(DateTime.now());
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_countdownChild(
context: context,
title: _launchDateDiff.inDays.toString().padLeft(2, '0'),
description: context.translate('spacex.home.tab.counter.day'),
),
Separator.spacer(),
_countdownChild(
context: context,
title: digitsToString(
(_launchDateDiff.inHours % 24) ~/ 10,
(_launchDateDiff.inHours % 24) % 10,
),
description: context.translate('spacex.home.tab.counter.hour'),
),
Separator.spacer(),
_countdownChild(
context: context,
title: digitsToString(
(_launchDateDiff.inMinutes % 60) ~/ 10,
(_launchDateDiff.inMinutes % 60) % 10,
),
description: context.translate('spacex.home.tab.counter.min'),
),
Separator.spacer(),
_countdownChild(
context: context,
title: digitsToString(
(_launchDateDiff.inSeconds % 60) ~/ 10,
(_launchDateDiff.inSeconds % 60) % 10,
),
description: context.translate('spacex.home.tab.counter.sec'),
),
],
);
}
Widget _countdownChild({
BuildContext context,
String title,
String description,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_countdownText(context: context, text: title, fontSize: 42),
_countdownText(context: context, text: description, fontSize: 16),
],
);
}
Widget _countdownText({BuildContext context, double fontSize, String text}) {
return Text(
text,
style: GoogleFonts.robotoMono(
fontSize: fontSize,
color: Colors.white,
shadows: [
Shadow(
blurRadius: 4,
color: Theme.of(context).primaryColor,
),
],
),
);
}
String digitsToString(int digit0, int digit1) =>
digit0.toString() + digit1.toString();
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/index.dart | export 'achievement_cell.dart';
export 'custom_page.dart';
export 'dialog_patreon.dart';
export 'error_view.dart';
export 'expand_list.dart';
export 'header_swiper.dart';
export 'index.dart';
export 'launch_cell.dart';
export 'launch_countdown.dart';
export 'loading_view.dart';
export 'profile_image.dart';
export 'responsive_page.dart';
export 'row_tap.dart';
export 'sliver_bar.dart';
export 'vehicle_cell.dart';
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/custom_page.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:row_collection/row_collection.dart';
import 'index.dart';
typedef RequestListBuilderLoaded<T> = List<Widget> Function(
BuildContext context,
RequestState<T> state,
T value,
);
/// Basic screen, which includes an [AppBar] widget.
/// Used when the desired page doesn't have slivers or reloading.
class SimplePage extends StatelessWidget {
final String title;
final Widget body, fab;
final List<Widget> actions;
const SimplePage({
@required this.title,
@required this.body,
this.fab,
this.actions,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
title,
style: GoogleFonts.rubik(fontWeight: FontWeight.w600),
),
centerTitle: true,
actions: actions,
),
body: body,
floatingActionButton: fab,
);
}
}
/// Basic page which has reloading properties.
/// It uses the [SimplePage] widget inside it.
///
/// This page also has state control via a `RequestCubit` parameter.
class RequestSimplePage<C extends RequestCubit, T> extends StatelessWidget {
final String title;
final Widget fab;
final RequestWidgetBuilderLoaded<T> childBuilder;
final List<Widget> actions;
const RequestSimplePage({
@required this.title,
@required this.childBuilder,
this.fab,
this.actions,
});
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: () => context.read<C>().loadData(),
child: SimplePage(
title: title,
fab: fab,
actions: actions,
body: RequestBuilder<C, T>(
onInit: (context, state) => Separator.none(),
onLoading: (context, state, value) => LoadingView(),
onLoaded: childBuilder,
onError: (context, state, error) => ErrorView<C>(),
),
),
);
}
}
/// This page is similar to `SimplePage`, in regards that it doesn't control state.
/// It holds a `SliverAppBar` and a plethera of others slivers inside.
class SliverPage extends StatelessWidget {
final String title;
final Widget header;
final List<Widget> children, actions;
final Map<String, String> popupMenu;
final ScrollController controller;
const SliverPage({
@required this.title,
@required this.header,
this.children,
this.actions,
this.popupMenu,
this.controller,
});
@override
Widget build(BuildContext context) {
return CustomScrollView(
key: PageStorageKey(title),
controller: controller,
slivers: <Widget>[
SliverBar(
title: title,
header: header,
actions: <Widget>[
if (popupMenu != null)
PopupMenuButton<String>(
itemBuilder: (context) => [
for (final item in popupMenu.keys)
PopupMenuItem(
value: item,
child: Text(FlutterI18n.translate(context, item)),
)
],
onSelected: (text) =>
Navigator.pushNamed(context, popupMenu[text]),
icon: IconShadow(Icons.adaptive.more),
),
if (actions != null) ...actions,
],
),
...children,
],
);
}
}
/// Basic slivery page which has reloading properties.
/// It uses the [SliverPage] widget inside it.
///
/// This page also has state control via a `RequestCubit` parameter.
class RequestSliverPage<C extends RequestCubit, T> extends StatelessWidget {
final String title;
final RequestWidgetBuilderLoaded<T> headerBuilder;
final RequestListBuilderLoaded<T> childrenBuilder;
final List<Widget> actions;
final Map<String, String> popupMenu;
final ScrollController controller;
const RequestSliverPage({
@required this.title,
@required this.headerBuilder,
@required this.childrenBuilder,
this.controller,
this.actions,
this.popupMenu,
});
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: () => context.read<C>().loadData(),
child: RequestBuilder<C, T>(
onInit: (context, state) => SliverPage(
controller: controller,
title: title,
header: Separator.none(),
actions: actions,
popupMenu: popupMenu,
),
onLoading: (context, state, value) => SliverPage(
controller: controller,
title: title,
header: value != null
? headerBuilder(context, state, value)
: Separator.none(),
actions: actions,
popupMenu: popupMenu,
children: value != null
? childrenBuilder(context, state, value)
: [LoadingSliverView()],
),
onLoaded: (context, state, value) => SliverPage(
controller: controller,
title: title,
header: headerBuilder(context, state, value),
actions: actions,
popupMenu: popupMenu,
children: childrenBuilder(context, state, value),
),
onError: (context, state, error) => SliverPage(
controller: controller,
title: title,
header: Separator.none(),
actions: actions,
popupMenu: popupMenu,
// ignore: prefer_const_literals_to_create_immutables
children: [ErrorSliverView<C>()],
),
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/row_tap.dart | import 'package:flutter/material.dart';
import 'package:row_item/row_item.dart';
import '../../utils/translate.dart';
/// Wrapper on [RowItem.tap]. Handles the behaviour of not having a description
/// and tap callback by using a differrent text style & data.
class RowTap extends StatelessWidget {
final String title, description, fallback;
final VoidCallback onTap;
const RowTap(
this.title,
this.description, {
Key key,
@required this.onTap,
this.fallback,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return RowItem.tap(
title,
description ?? fallback ?? context.translate('spacex.other.unknown'),
descriptionStyle: TextStyle(
decoration: description != null
? TextDecoration.underline
: TextDecoration.none,
),
onTap: description == null ? null : onTap,
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/error_view.dart | import 'package:big_tip/big_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../../utils/index.dart';
/// Widget that tells the user that there's been an error in a network process.
/// It allows the user to perform a reload action.
class ErrorView<C extends RequestCubit> extends StatelessWidget {
const ErrorView({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BigTip(
subtitle: Text(
context.translate('spacex.other.loading_error.message'),
style: Theme.of(context).textTheme.subtitle1,
),
action: Text(
context.translate('spacex.other.loading_error.reload'),
style: Theme.of(context).textTheme.subtitle1.copyWith(
color: Theme.of(context).accentColor,
fontWeight: FontWeight.bold,
),
),
actionCallback: () => context.read<C>().loadData(),
child: Icon(Icons.cloud_off),
);
}
}
/// Presents the `ErrorView` widget inside a slivered widget.
///
/// Tells the user that there's been an error in a network process.
/// It allows the user to perform a reload action.
class ErrorSliverView<C extends RequestCubit> extends StatelessWidget {
const ErrorSliverView({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverFillRemaining(
child: ErrorView<C>(),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/vehicle_cell.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:row_collection/row_collection.dart';
import '../../models/index.dart';
import '../views/vehicles/index.dart';
import 'index.dart';
class VehicleCell extends StatelessWidget {
final Vehicle vehicle;
const VehicleCell(this.vehicle, {Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
ListCell(
leading: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(8)),
child: ProfileImage.small(vehicle.getProfilePhoto),
),
title: vehicle.name,
subtitle: vehicle.subtitle(context),
onTap: () => Navigator.pushNamed(
context,
VehiclePage.route,
arguments: {'id': vehicle.id},
),
),
Separator.divider(indent: 72)
]);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/sliver_bar.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
/// Custom sliver app bar used in Sliver views.
/// It collapses when user scrolls down.
class SliverBar extends StatelessWidget {
static const double heightRatio = 0.3;
final String title;
final Widget header;
final num height;
final List<Widget> actions;
final PopupMenuItemBuilder<String> menuItemBuilder;
final PopupMenuItemSelected<String> onMenuItemSelected;
const SliverBar({
this.title,
this.header,
this.height = heightRatio,
this.actions,
this.menuItemBuilder,
this.onMenuItemSelected,
});
@override
Widget build(BuildContext context) {
final parentRoute = ModalRoute.of(context);
final useCloseButton =
parentRoute is PageRoute<dynamic> && parentRoute.fullscreenDialog;
return SliverAppBar(
expandedHeight: MediaQuery.of(context).size.height * height,
leading: Navigator.of(context).canPop()
? useCloseButton
? IconButton(
icon: const IconShadow(Icons.close),
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
onPressed: () => Navigator.of(context).pop(),
)
: IconButton(
icon: IconShadow(Icons.adaptive.arrow_back),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
onPressed: () => Navigator.of(context).pop(),
)
: null,
actions: [
...actions,
if (menuItemBuilder != null && onMenuItemSelected != null)
PopupMenuButton<String>(
itemBuilder: menuItemBuilder,
onSelected: onMenuItemSelected,
icon: IconShadow(Icons.adaptive.more),
),
],
pinned: true,
flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
// Using title constraining, because Flutter doesn't do this automatically.
// Open issue: [https://github.com/flutter/flutter/issues/14227]
title: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.55,
),
child: Text(
title,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
maxLines: 1,
style: GoogleFonts.rubik(
fontWeight: FontWeight.w600,
shadows: [
Shadow(
blurRadius: 4,
color: Theme.of(context).primaryColor,
),
],
),
),
),
background: header,
),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/loading_view.dart | import 'package:flutter/material.dart';
/// Basic loading view, with a `CircularProgressIndicator` at the center.
class LoadingView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: const CircularProgressIndicator(),
);
}
}
/// Places a `CircularProgressIndicator` widget in the middle of a slivered widget.
class LoadingSliverView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SliverFillRemaining(
child: LoadingView(),
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib/ui | mirrored_repositories/spacex-go/lib/ui/widgets/header_swiper.dart | import 'package:cherry_components/cherry_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';
import '../../cubits/index.dart';
import '../../utils/index.dart';
/// Used as a sliver header, in the [background] parameter.
/// It allows the user to scroll through multiple shots.
class SwiperHeader extends StatefulWidget {
final List<String> list;
final IndexedWidgetBuilder builder;
const SwiperHeader({
Key key,
@required this.list,
this.builder,
}) : super(key: key);
@override
_SwiperHeaderState createState() => _SwiperHeaderState();
}
class _SwiperHeaderState extends State<SwiperHeader> {
List<String> auxList;
@override
void initState() {
super.initState();
auxList = [];
}
@override
void didChangeDependencies() {
auxList = selectQuality(context);
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Swiper(
itemCount: widget.list.length,
itemBuilder:
widget.builder ?? (context, index) => CacheImage(auxList[index]),
curve: Curves.easeInOutCubic,
autoplayDelay: 5000,
autoplay: true,
duration: 850,
onTap: (index) => context.openUrl(auxList[index]),
);
}
/// Returns the image list, with the desire image quality
List<String> selectQuality(BuildContext context) {
// Reg exps to check if the image URL is from Flickr
final RegExp qualityRegEx = RegExp(r'(_[a-z])*\.jpg$');
final RegExp flickrRegEx = RegExp(
r'^https:\/\/.+\.staticflickr\.com\/[0-9]+\/[0-9]+_.+_.+\.jpg$',
);
// Getting the desire image quality tag
final int qualityIndex = ImageQuality.values
.indexOf(context.watch<ImageQualityCubit>().imageQuality);
final String qualityTag = ['_w', '_z', '_b'][qualityIndex];
return [
for (final url in widget.list)
flickrRegEx.hasMatch(url)
? url.replaceFirst(qualityRegEx, '$qualityTag.jpg')
: url
];
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/launches.dart | import 'package:dio/dio.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../utils/api_query.dart';
import '../utils/index.dart';
/// Services that retrieves information about SpaceX's launches.
class LaunchesService extends BaseService<Dio> {
const LaunchesService(Dio client) : super(client);
Future<Response> getLaunches() async {
return client.post(
Url.launches,
data: ApiQuery.launch,
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/vehicles.dart | import 'package:dio/dio.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../utils/index.dart';
/// Services that retrieves information about SpaceX's vehicles.
class VehiclesService extends BaseService<Dio> {
const VehiclesService(Dio client) : super(client);
Future<Response> getRoadster() async {
return client.post(
Url.roadster,
data: ApiQuery.roadsterVehicle,
);
}
Future<Response> getDragons() async {
return client.post(
Url.dragons,
data: ApiQuery.dragonVehicle,
);
}
Future<Response> getRockets() async {
return client.post(
Url.rockets,
data: ApiQuery.rocketVehicle,
);
}
Future<Response> getShips() async {
return client.post(
Url.ships,
data: ApiQuery.shipVehicle,
);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/index.dart | export 'achievements.dart';
export 'changelog.dart';
export 'company.dart';
export 'launches.dart';
export 'vehicles.dart';
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/achievements.dart | import 'package:dio/dio.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../utils/index.dart';
/// Services that retrieves a list featuring the latest SpaceX acomplishments.
class AchievementsService extends BaseService<Dio> {
const AchievementsService(Dio client) : super(client);
Future<Response> getAchievements() async {
return client.get(Url.companyAchievements);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/company.dart | import 'package:dio/dio.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../utils/index.dart';
/// Services that retrieves information about the company itself.
class CompanyService extends BaseService<Dio> {
const CompanyService(Dio client) : super(client);
Future<Response> getCompanyInformation() async {
return client.get(Url.companyInformation);
}
}
| 0 |
mirrored_repositories/spacex-go/lib | mirrored_repositories/spacex-go/lib/services/changelog.dart | import 'package:dio/dio.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import '../utils/index.dart';
/// Services that retrieves information about the app's changelog.
class ChangelogService extends BaseService<Dio> {
const ChangelogService(Dio client) : super(client);
Future<Response> getChangelog() async {
return client.get(Url.changelog);
}
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/image_quality_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:cherry/cubits/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/hydrated.dart';
void main() {
initHydratedBloc();
group('ImageQualityCubit', () {
ImageQualityCubit cubit;
setUp(() {
cubit = ImageQualityCubit();
});
test('has initial value', () async {
expect(cubit.state, ImageQuality.medium);
expect(cubit.imageQuality, ImageQuality.medium);
});
group('toJson/fromJson', () {
test('work properly', () {
expect(
cubit.fromJson(cubit.toJson(cubit.state)),
cubit.state,
);
});
});
blocTest<ImageQualityCubit, ImageQuality>(
'can change its state',
build: () => cubit,
act: (cubit) {
cubit.imageQuality = ImageQuality.high;
cubit.imageQuality = ImageQuality.low;
},
expect: () => [
ImageQuality.high,
ImageQuality.low,
],
);
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/notifications_test.dart | import 'package:cherry/cubits/index.dart';
import 'package:cherry/models/index.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:platform/platform.dart';
import 'helpers/hydrated.dart';
class MockBuildContext extends Mock implements BuildContext {}
void main() {
initHydratedBloc();
group('NotificationsCubit', () {
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
final log = <MethodCall>[];
NotificationsCubit cubit;
FlutterLocalNotificationsPlugin service;
MockBuildContext context;
DateTime currentDateTime;
setUp(() {
tz.initializeTimeZones();
currentDateTime = DateTime.now().toUtc();
context = MockBuildContext();
service = FlutterLocalNotificationsPlugin.private(
FakePlatform(operatingSystem: 'ios'),
);
channel.setMockMethodCallHandler((methodCall) {
log.add(methodCall);
if (methodCall.method == 'pendingNotificationRequests') {
return Future<List<Map<String, Object>>>.value([]);
} else if (methodCall.method == 'getNotificationAppLaunchDetails') {
return Future<Map<String, Object>>.value({});
}
return Future<void>.value();
});
cubit = NotificationsCubit(
service,
notificationDetails: NotificationDetails(),
initializationSettings: InitializationSettings(),
);
});
tearDown(() {
log.clear();
});
group('testing arguments & init', () {
test('checks if service is null', () {
expect(() => NotificationsCubit(null), throwsAssertionError);
});
test('checks notifications initialization', () async {
await cubit.init();
});
});
group('toJson/fromJson', () {
test('work properly', () {
expect(
cubit.fromJson(cubit.toJson(cubit.state)),
cubit.state,
);
});
});
group('testing date saving', () {
test('saves new launch date', () {
cubit.setNextLaunchDate(DateTime(1970));
expect(cubit.state, DateTime(1970));
});
test('checks current launch date', () {
cubit.setNextLaunchDate(DateTime(1970));
expect(cubit.needsToUpdate(DateTime(1971)), true);
expect(cubit.needsToUpdate(DateTime(1970)), false);
cubit.setNextLaunchDate(null);
expect(cubit.needsToUpdate(DateTime(1970)), true);
expect(cubit.needsToUpdate(DateTime(1971)), true);
});
});
group('scheduling notifications', () {
test(
"correctly checks that the launch date is not concrete enough",
() async {
await cubit.updateNotifications(
MockBuildContext(),
nextLaunch: _getMockLaunch(
launchDate: currentDateTime.add(Duration(days: 5)),
datePrecision: 'day',
),
);
expect(cubit.state, null);
expect(log.length, isZero);
},
);
test(
"correctly deletes previous notifications, but launch date is not concrete enough",
() async {
cubit.setNextLaunchDate(DateTime(1970));
await cubit.updateNotifications(
MockBuildContext(),
nextLaunch: _getMockLaunch(
launchDate: currentDateTime.add(Duration(days: 5)),
datePrecision: 'day',
),
);
expect(cubit.state, null);
expect(log.length, 1);
expect(log[0], isMethodCall('cancelAll', arguments: null));
},
);
test(
"correctly adds the 30-mins notification to the system",
() async {
await cubit.updateNotifications(
context,
nextLaunch: _getMockLaunch(
launchDate: currentDateTime.add(Duration(minutes: 31)),
datePrecision: 'hour',
),
);
expect(cubit.state, currentDateTime.add(Duration(minutes: 31)));
expect(log.length, 1);
expect(
log[0],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 2,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(minutes: 31)),
tz.UTC,
).subtract(Duration(minutes: 30)),
),
},
),
);
},
);
test(
"correctly adds the 30-mins and 1-hour notifications to the system",
() async {
await cubit.updateNotifications(
context,
nextLaunch: _getMockLaunch(
launchDate: currentDateTime.add(Duration(hours: 2)),
datePrecision: 'hour',
),
);
expect(cubit.state, currentDateTime.add(Duration(hours: 2)));
expect(log.length, 2);
expect(
log[0],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 1,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(hours: 2)),
tz.UTC,
).subtract(Duration(hours: 1)),
),
},
),
);
expect(
log[1],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 2,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(hours: 2)),
tz.UTC,
).subtract(Duration(minutes: 30)),
),
},
),
);
},
);
test(
"correctly update all notifications with no previous notifications",
() async {
await cubit.updateNotifications(
context,
nextLaunch: _getMockLaunch(
launchDate: currentDateTime.add(Duration(days: 5)),
datePrecision: 'hour',
),
);
expect(cubit.state, currentDateTime.add(Duration(days: 5)));
expect(log.length, 3);
expect(
log[0],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 0,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(days: 5)),
tz.UTC,
).subtract(Duration(days: 1)),
),
},
),
);
expect(
log[1],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 1,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(days: 5)),
tz.UTC,
).subtract(Duration(hours: 1)),
),
},
),
);
expect(
log[2],
isMethodCall(
'zonedSchedule',
arguments: <String, Object>{
'id': 2,
'title': 'spacex.notifications.launches.title',
'body': 'spacex.notifications.launches.body',
'platformSpecifics': <String, Object>{},
'payload': '',
'uiLocalNotificationDateInterpretation': 1,
'timeZoneName': 'UTC',
'scheduledDateTime': _convertDateToISO8601String(
tz.TZDateTime.from(
currentDateTime.add(Duration(days: 5)),
tz.UTC,
).subtract(Duration(minutes: 30)),
),
},
),
);
},
);
});
});
}
Launch _getMockLaunch({DateTime launchDate, String datePrecision}) {
return Launch(
launchDate: launchDate,
datePrecision: datePrecision,
rocket: RocketDetails(
name: 'RocketName',
payloads: const [
Payload(
name: 'PayloadName',
orbit: 'PayloadOrbit',
)
],
),
);
}
String _convertDateToISO8601String(tz.TZDateTime dateTime) {
String _twoDigits(int n) {
if (n >= 10) {
return '$n';
}
return '0$n';
}
String _fourDigits(int n) {
final int absN = n.abs();
final String sign = n < 0 ? '-' : '';
if (absN >= 1000) {
return '$n';
}
if (absN >= 100) {
return '${sign}0$absN';
}
if (absN >= 10) {
return '${sign}00$absN';
}
return '${sign}000$absN';
}
return '${_fourDigits(dateTime.year)}-${_twoDigits(dateTime.month)}-${_twoDigits(dateTime.day)}T${_twoDigits(dateTime.hour)}:${_twoDigits(dateTime.minute)}:${_twoDigits(dateTime.second)}'; // ignore: lines_longer_than_80_chars
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/launches_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockLaunchesRepository extends Mock implements LaunchesRepository {}
void main() {
group('LaunchesCubit', () {
LaunchesCubit cubit;
MockLaunchesRepository repository;
setUp(() {
repository = MockLaunchesRepository();
cubit = LaunchesCubit(repository);
});
tearDown(() {
cubit.close();
});
group('fetchData', () {
blocTest<LaunchesCubit, RequestState>(
'fetches data correctly',
build: () {
when(repository.fetchData()).thenAnswer(
(_) => Future.value(const [
[Launch(id: '1')]
]),
);
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<List<Launch>>>.loading(),
RequestState<List<List<Launch>>>.loaded(const [
[Launch(id: '1')]
]),
],
);
blocTest<LaunchesCubit, RequestState>(
'can throw an exception',
build: () {
when(repository.fetchData()).thenThrow(Exception('wtf'));
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<List<Launch>>>.loading(),
RequestState<List<List<Launch>>>.error(Exception('wtf').toString()),
],
);
});
group('getter', () {
test('getLaunch works correctly', () async {
when(repository.fetchData()).thenAnswer(
(_) => Future.value([
[Launch(id: '1')],
[Launch(id: '2')]
]),
);
await cubit.loadData();
expect(cubit.getLaunch('1'), Launch(id: '1'));
});
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/achievements_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockAchievementsRepository extends Mock
implements AchievementsRepository {}
void main() {
group('AchievementsCubit', () {
AchievementsCubit cubit;
MockAchievementsRepository repository;
setUp(() {
repository = MockAchievementsRepository();
cubit = AchievementsCubit(repository);
});
tearDown(() {
cubit.close();
});
group('fetchData', () {
blocTest<AchievementsCubit, RequestState>(
'fetches data correctly',
build: () {
when(repository.fetchData()).thenAnswer(
(_) => Future.value(const [Achievement(id: '1')]),
);
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<Achievement>>.loading(),
RequestState<List<Achievement>>.loaded(const [Achievement(id: '1')]),
],
);
blocTest<AchievementsCubit, RequestState>(
'can throw an exception',
build: () {
when(repository.fetchData()).thenThrow(Exception('wtf'));
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<Achievement>>.loading(),
RequestState<List<Achievement>>.error(Exception('wtf').toString()),
],
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/browser_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:cherry/cubits/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/hydrated.dart';
void main() {
initHydratedBloc();
group('BrowserCubit', () {
BrowserCubit cubit;
setUp(() {
cubit = BrowserCubit();
});
test('has initial value', () async {
expect(cubit.state, BrowserType.inApp);
expect(cubit.browserType, BrowserType.inApp);
});
group('toJson/fromJson', () {
test('work properly', () {
expect(
cubit.fromJson(cubit.toJson(cubit.state)),
cubit.state,
);
});
});
blocTest<BrowserCubit, BrowserType>(
'can change its state',
build: () => cubit,
act: (cubit) {
cubit.browserType = BrowserType.system;
},
expect: () => [
BrowserType.system,
],
);
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/changelog_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'helpers/hydrated.dart';
class MockChangelogRepository extends Mock implements ChangelogRepository {}
void main() {
initHydratedBloc();
group('ChangelogCubit', () {
ChangelogCubit cubit;
MockChangelogRepository repository;
setUp(() {
repository = MockChangelogRepository();
cubit = ChangelogCubit(repository);
});
tearDown(() {
cubit.close();
});
group('toJson/fromJson', () {
test('work properly', () {
expect(
cubit.fromJson(cubit.toJson(cubit.state)),
cubit.state,
);
});
});
group('fetchData', () {
blocTest<ChangelogCubit, RequestState>(
'fetches data correctly',
build: () {
when(repository.fetchData()).thenAnswer(
(_) => Future.value('Lorem'),
);
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<String>.loading(),
RequestState<String>.loaded('Lorem'),
],
);
blocTest<ChangelogCubit, RequestState>(
'can throw an exception',
build: () {
when(repository.fetchData()).thenThrow(Exception('wtf'));
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<String>.loading(),
RequestState<String>.error(Exception('wtf').toString()),
],
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/theme_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/hydrated.dart';
void main() {
initHydratedBloc();
group('ThemeCubit', () {
ThemeCubit cubit;
setUp(() {
cubit = ThemeCubit();
});
test('has initial value', () async {
expect(cubit.state, ThemeState.system);
expect(cubit.theme, ThemeState.system);
});
group('toJson/fromJson', () {
test('work properly', () {
expect(
cubit.fromJson(cubit.toJson(cubit.state)),
cubit.state,
);
});
});
blocTest<ThemeCubit, ThemeState>(
'can change its state',
build: () => cubit,
act: (cubit) => cubit.theme = ThemeState.black,
expect: () => [
ThemeState.black,
],
);
test('has default light theme', () async {
expect(cubit.lightTheme, Style.light);
});
test('has default dark theme', () async {
expect(cubit.darkTheme, Style.dark);
cubit.theme = ThemeState.black;
expect(cubit.darkTheme, Style.black);
});
test('returns ThemeMode correctly', () async {
cubit.theme = ThemeState.system;
expect(cubit.themeMode, ThemeMode.system);
cubit.theme = ThemeState.light;
expect(cubit.themeMode, ThemeMode.light);
cubit.theme = ThemeState.dark;
expect(cubit.themeMode, ThemeMode.dark);
cubit.theme = ThemeState.black;
expect(cubit.themeMode, ThemeMode.dark);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/company_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockCompanyRepository extends Mock implements CompanyRepository {}
void main() {
group('CompanyCubit', () {
CompanyCubit cubit;
MockCompanyRepository repository;
setUp(() {
repository = MockCompanyRepository();
cubit = CompanyCubit(repository);
});
tearDown(() {
cubit.close();
});
group('fetchData', () {
blocTest<CompanyCubit, RequestState>(
'fetches data correctly',
build: () {
when(repository.fetchData()).thenAnswer(
(_) => Future.value(CompanyInfo(id: '1')),
);
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<CompanyInfo>.loading(),
RequestState<CompanyInfo>.loaded(CompanyInfo(id: '1')),
],
);
blocTest<CompanyCubit, RequestState>(
'can throw an exception',
build: () {
when(repository.fetchData()).thenThrow(Exception('wtf'));
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<CompanyInfo>.loading(),
RequestState<CompanyInfo>.error(Exception('wtf').toString()),
],
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/request_state_test.dart | import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Testing constructor values', () {
test('RequestState.init()', () {
expect(RequestState.init().status, RequestStatus.init);
expect(RequestState.init().value, null);
expect(RequestState.init().errorMessage, null);
});
test('RequestState.loading()', () {
expect(RequestState.loading().status, RequestStatus.loading);
expect(RequestState.loading().value, null);
expect(RequestState.loading().errorMessage, null);
});
test('RequestState.loaded()', () {
expect(RequestState.loaded('Lorem').status, RequestStatus.loaded);
expect(RequestState.loaded('Lorem').value, 'Lorem');
expect(RequestState.loaded('Lorem').errorMessage, null);
});
test('RequestState.error()', () {
expect(RequestState.error('Lorem').status, RequestStatus.error);
expect(RequestState.error('Lorem').value, null);
expect(RequestState.error('Lorem').errorMessage, 'Lorem');
});
});
group('Testing serialization', () {
test('RequestState.fromJson()', () {
expect(
RequestState.fromJson({
'status': RequestStatus.init.index,
'value': null,
'errorMessage': null,
}),
RequestState.init(),
);
expect(
RequestState.fromJson({
'status': RequestStatus.loading.index,
'value': null,
'errorMessage': null,
}),
RequestState.loading(),
);
expect(
RequestState<String>.fromJson({
'status': RequestStatus.loaded.index,
'value': 'Lorem',
'errorMessage': null,
}),
RequestState.loaded('Lorem'),
);
expect(
RequestState.fromJson({
'status': RequestStatus.error.index,
'value': null,
'errorMessage': 'Lorem',
}),
RequestState.error('Lorem'),
);
});
test('RequestState.toJson()', () {
var state = RequestState.init();
expect(state.toJson(), {
'status': RequestStatus.init.index,
'value': null,
'errorMessage': null,
});
state = RequestState.loading();
expect(state.toJson(), {
'status': RequestStatus.loading.index,
'value': null,
'errorMessage': null,
});
state = RequestState.loaded('Lorem');
expect(state.toJson(), {
'status': RequestStatus.loaded.index,
'value': 'Lorem',
'errorMessage': null,
});
state = RequestState.error('Lorem');
expect(state.toJson(), {
'status': RequestStatus.error.index,
'value': null,
'errorMessage': 'Lorem',
});
});
});
test('Testning equals operator', () {
expect(RequestState.init() == RequestState.init(), true);
expect(RequestState.init() == RequestState.loading(), false);
expect(RequestState.loaded('Lorem') == RequestState.loaded('Lorem'), true);
expect(
RequestState.loaded('Lorem') == RequestState.loaded('Lorem123'),
false,
);
expect(RequestState.error('Lorem') == RequestState.error('Lorem'), true);
expect(
RequestState.error('Lorem') == RequestState.error('Lorem123'),
false,
);
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/cubits/vehicles_test.dart | import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_request_bloc/flutter_request_bloc.dart';
import 'package:cherry/cubits/index.dart';
import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockVehiclesRepository extends Mock implements VehiclesRepository {}
void main() {
group('VehiclesCubit', () {
VehiclesCubit cubit;
MockVehiclesRepository repository;
setUp(() {
repository = MockVehiclesRepository();
cubit = VehiclesCubit(repository);
});
tearDown(() {
cubit.close();
});
group('fetchData', () {
blocTest<VehiclesCubit, RequestState>(
'fetches data correctly',
build: () {
when(repository.fetchData()).thenAnswer(
(_) => Future.value(const [RocketVehicle(id: '1')]),
);
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<Vehicle>>.loading(),
RequestState<List<Vehicle>>.loaded(const [RocketVehicle(id: '1')]),
],
);
blocTest<VehiclesCubit, RequestState>(
'can throw an exception',
build: () {
when(repository.fetchData()).thenThrow(Exception('wtf'));
return cubit;
},
act: (cubit) async => cubit.loadData(),
verify: (_) => verify(repository.fetchData()).called(2),
expect: () => [
RequestState<List<Vehicle>>.loading(),
RequestState<List<Vehicle>>.error(Exception('wtf').toString()),
],
);
});
group('getter', () {
test('getVehicle works correctly', () async {
when(repository.fetchData()).thenAnswer(
(_) => Future.value(const [RocketVehicle(id: '1')]),
);
await cubit.loadData();
expect(cubit.getVehicle('1'), RocketVehicle(id: '1'));
});
});
});
}
| 0 |
mirrored_repositories/spacex-go/test/cubits | mirrored_repositories/spacex-go/test/cubits/helpers/hydrated.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:mockito/mockito.dart';
class MockStorage extends Mock implements Storage {
@override
Future<void> write(String key, dynamic value) async {}
}
final hydratedStorage = MockStorage();
void initHydratedBloc() {
TestWidgetsFlutterBinding.ensureInitialized();
HydratedBloc.storage = hydratedStorage;
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/company_info_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('CompanyInfo', () {
test('is correctly generated from a JSON', () {
expect(
CompanyInfo.fromJson(const {
'headquarters': {
'address': 'Rocket Road',
'city': 'Hawthorne',
'state': 'California'
},
'links': {
'website': 'https://www.spacex.com/',
'flickr': 'https://www.flickr.com/photos/spacex/',
'twitter': 'https://twitter.com/SpaceX',
'elon_twitter': 'https://twitter.com/elonmusk'
},
'name': 'SpaceX',
'founder': 'Elon Musk',
'founded': 2002,
'employees': 8000,
'vehicles': 3,
'launch_sites': 3,
'test_sites': 1,
'ceo': 'Elon Musk',
'cto': 'Elon Musk',
'coo': 'Gwynne Shotwell',
'cto_propulsion': 'Tom Mueller',
'valuation': 52000000000,
'summary':
'SpaceX designs, manufactures and launches advanced rockets and spacecraft. The company was founded in 2002 to revolutionize space technology, with the ultimate goal of enabling people to live on other planets.',
'id': '5eb75edc42fea42237d7f3ed'
}),
CompanyInfo(
city: 'Hawthorne',
state: 'California',
fullName: 'Space Exploration Technologies Corporation',
name: 'SpaceX',
founder: 'Elon Musk',
founded: 2002,
employees: 8000,
ceo: 'Elon Musk',
cto: 'Elon Musk',
coo: 'Gwynne Shotwell',
valuation: 52000000000,
details:
'SpaceX designs, manufactures and launches advanced rockets and spacecraft. The company was founded in 2002 to revolutionize space technology, with the ultimate goal of enabling people to live on other planets.',
id: '5eb75edc42fea42237d7f3ed',
),
);
});
test('correctly return valuation', () {
expect(
CompanyInfo(valuation: 100).getValuation,
'\$100',
);
});
test('correctly returns founder date', () {
expect(
CompanyInfo().getFounderDate(MockBuildContext()),
'spacex.company.founded',
);
});
test('correctly return location', () {
expect(
CompanyInfo(
city: 'City',
state: 'State',
).getLocation,
'City, State',
);
});
test('correctly return number of employees', () {
expect(
CompanyInfo(employees: 100).getEmployees,
'100',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/ship_vehicle_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('ShipVehicle', () {
test('is correctly generated from a JSON', () {
expect(
ShipVehicle.fromJson(const {
'model': 'Boat',
'type': 'High Speed Craft',
'roles': ['Fairing Recovery'],
'mass_kg': 449964,
'year_built': 2015,
'home_port': 'Port Canaveral',
'status': 'status',
'speed_kn': 200,
'link':
'https://www.marinetraffic.com/en/ais/details/ships/shipid:3439091/mmsi:368099550/imo:9744465/vessel:GO_MS_TREE',
'image': 'https://i.imgur.com/MtEgYbY.jpg',
'launches': [
{
'flight_number': 50,
'name': 'KoreaSat 5A',
'id': '5eb87d0dffd86e000604b35b'
}
],
'name': 'GO Ms Tree',
'active': true,
'id': '5ea6ed2e080df4000697c908'
}),
ShipVehicle(
id: '5ea6ed2e080df4000697c908',
name: 'GO Ms Tree',
url:
'https://www.marinetraffic.com/en/ais/details/ships/shipid:3439091/mmsi:368099550/imo:9744465/vessel:GO_MS_TREE',
mass: 449964,
active: true,
firstFlight: DateTime(2015),
photos: const [
'https://i.imgur.com/MtEgYbY.jpg',
],
model: 'Boat',
use: 'High Speed Craft',
roles: const [
'Fairing Recovery',
],
missions: const [
LaunchDetails(
flightNumber: 50,
name: 'KoreaSat 5A',
id: '5eb87d0dffd86e000604b35b',
)
],
homePort: 'Port Canaveral',
status: 'status',
speed: 200,
),
);
});
test('correctly returns roles', () {
expect(
ShipVehicle(roles: const ['', '']).hasSeveralRoles,
true,
);
});
test('correctly returns primary role', () {
expect(
ShipVehicle(roles: const ['role']).primaryRole,
'role',
);
});
test('correctly returns primary role', () {
expect(
ShipVehicle(roles: const ['role', 'role2']).secondaryRole,
'role2',
);
});
test('correctly check mission number', () {
expect(
ShipVehicle(missions: const []).hasMissions,
false,
);
});
test('correctly returns built date', () {
expect(
ShipVehicle(firstFlight: DateTime(2015)).getBuiltFullDate,
'2015',
);
});
test('correctly returns subtitle', () {
expect(
ShipVehicle(firstFlight: DateTime(2015)).subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.ship_built',
);
});
test('correctly returns subtitle', () {
expect(
ShipVehicle().getModel(MockBuildContext()),
'spacex.other.unknown',
);
expect(
ShipVehicle(model: 'Lorem').getModel(MockBuildContext()),
'Lorem',
);
});
test('correctly returns status', () {
expect(
ShipVehicle().getStatus(MockBuildContext()),
'spacex.other.unknown',
);
expect(
ShipVehicle(status: 'Lorem').getStatus(MockBuildContext()),
'Lorem',
);
});
test('correctly returns speed', () {
expect(
ShipVehicle().getSpeed(MockBuildContext()),
'spacex.other.unknown',
);
expect(
ShipVehicle(speed: 100).getSpeed(MockBuildContext()),
'185.2 km/h',
);
});
test('correctly returns mass', () {
expect(
ShipVehicle().getMass(MockBuildContext()),
'spacex.other.unknown',
);
expect(
ShipVehicle(mass: 100).getMass(MockBuildContext()),
'100 kg',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/roadster_vehicle_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart';
import 'mock_context.dart';
void main() {
group('RoadsterVehicle', () {
test('is correctly generated from a JSON', () {
expect(
RoadsterVehicle.fromJson(const {
"flickr_images": [
"https://farm5.staticflickr.com/4615/40143096241_11128929df_b.jpg",
"https://farm5.staticflickr.com/4702/40110298232_91b32d0cc0_b.jpg",
"https://farm5.staticflickr.com/4676/40110297852_5e794b3258_b.jpg",
"https://farm5.staticflickr.com/4745/40110304192_6e3e9a7a1b_b.jpg"
],
"name": "Elon Musk's Tesla Roadster",
"launch_date_utc": "2018-02-06T20:45:00.000Z",
"launch_date_unix": 1517949900,
"launch_mass_kg": 1350,
"launch_mass_lbs": 2976,
"norad_id": 43205,
"epoch_jd": 2459099.747048611,
"orbit_type": "heliocentric",
"apoapsis_au": 1.663953958687046,
"periapsis_au": 0.9858147198091061,
"semi_major_axis_au": 251.4894388260824,
"eccentricity": 0.2559239394673542,
"inclination": 1.077447168391629,
"longitude": 317.0814558060362,
"periapsis_arg": 177.5319554749398,
"period_days": 557.0130583804103,
"speed_kph": 81565.80012,
"speed_mph": 50682.62278636452,
"earth_distance_km": 91218798.05943623,
"earth_distance_mi": 56680715.76898995,
"mars_distance_km": 22540919.9995336,
"mars_distance_mi": 14006274.001030194,
"wikipedia":
"https://en.wikipedia.org/wiki/Elon_Musk%27s_Tesla_Roadster",
"video": "https://youtu.be/wbSwFU6tY1c",
"details":
"Elon Musk's Tesla Roadster is an electric sports car that served as the dummy payload for the February 2018 Falcon Heavy test flight and is now an artificial satellite of the Sun. Starman, a mannequin dressed in a spacesuit, occupies the driver's seat. The car and rocket are products of Tesla and SpaceX. This 2008-model Roadster was previously used by Musk for commuting, and is the only consumer car sent into space.",
"id": "5eb75f0842fea42237d7f3f4"
}),
RoadsterVehicle(
id: '5eb75f0842fea42237d7f3f4',
description:
"Elon Musk's Tesla Roadster is an electric sports car that served as the dummy payload for the February 2018 Falcon Heavy test flight and is now an artificial satellite of the Sun. Starman, a mannequin dressed in a spacesuit, occupies the driver's seat. The car and rocket are products of Tesla and SpaceX. This 2008-model Roadster was previously used by Musk for commuting, and is the only consumer car sent into space.",
url: 'https://en.wikipedia.org/wiki/Elon_Musk%27s_Tesla_Roadster',
mass: 1350,
firstFlight: DateTime.parse('2018-02-06T20:45:00.000Z'),
photos: const [
"https://farm5.staticflickr.com/4615/40143096241_11128929df_b.jpg",
"https://farm5.staticflickr.com/4702/40110298232_91b32d0cc0_b.jpg",
"https://farm5.staticflickr.com/4676/40110297852_5e794b3258_b.jpg",
"https://farm5.staticflickr.com/4745/40110304192_6e3e9a7a1b_b.jpg"
],
orbit: 'heliocentric',
video: 'https://youtu.be/wbSwFU6tY1c',
apoapsis: 1.663953958687046,
periapsis: 0.9858147198091061,
inclination: 1.077447168391629,
longitude: 317.0814558060362,
period: 557.0130583804103,
speed: 81565.80012,
earthDistance: 91218798.05943623,
marsDistance: 22540919.9995336,
),
);
});
test('correctly retuns Mars distance', () {
expect(
RoadsterVehicle(marsDistance: 100).getMarsDistance,
'100 km',
);
});
test('correctly retuns Earth distance', () {
expect(
RoadsterVehicle(earthDistance: 100).getEarthDistance,
'100 km',
);
});
test('correctly retuns speed', () {
expect(
RoadsterVehicle(speed: 100).getSpeed,
'100 km/h',
);
});
test('correctly retuns longitude', () {
expect(
RoadsterVehicle(longitude: 100).getLongitude,
'100°',
);
});
test('correctly retuns inclination', () {
expect(
RoadsterVehicle(inclination: 100).getInclination,
'100°',
);
});
test('correctly retuns periapsis', () {
expect(
RoadsterVehicle(periapsis: 100).getPeriapsis,
'100 ua',
);
});
test('correctly retuns apoapsis', () {
expect(
RoadsterVehicle(apoapsis: 100).getApoapsis,
'100 ua',
);
});
test('correctly retuns orbit', () {
expect(
RoadsterVehicle(orbit: 'test').getOrbit,
'Test',
);
});
test('correctly retuns period', () {
expect(
RoadsterVehicle(period: 100).getPeriod(MockBuildContext()),
'spacex.vehicle.roadster.orbit.days',
);
});
test('correctly retuns subtitle text', () {
expect(
RoadsterVehicle(firstFlight: DateTime.now())
.subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.launched',
);
});
test('correctly retuns full launch date', () {
expect(
RoadsterVehicle(firstFlight: DateTime.now())
.getFullLaunchDate(MockBuildContext()),
'spacex.vehicle.subtitle.launched',
);
});
test('correctly retuns full launch date', () {
expect(
RoadsterVehicle(firstFlight: DateTime.now())
.getLaunchDate(MockBuildContext()),
DateFormat.yMMMMd().format(DateTime.now()),
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/dragon_vehicle_test.dart | import 'dart:math';
import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('DragonVehicle', () {
test('is correctly generated from a JSON', () {
expect(
DragonVehicle.fromJson(const {
'launch_payload_mass': {'kg': 6000},
'return_payload_mass': {'kg': 3000},
'height_w_trunk': {'meters': 7.2},
'diameter': {'meters': 3.7},
'first_flight': '2010-12-08',
'flickr_images': [
'https://i.imgur.com/9fWdwNv.jpg',
'https://live.staticflickr.com/8578/16655995541_7817565ea9_k.jpg',
'https://farm3.staticflickr.com/2815/32761844973_4b55b27d3c_b.jpg',
'https://farm9.staticflickr.com/8618/16649075267_d18cbb4342_b.jpg'
],
'name': 'Dragon 1',
'type': 'capsule',
'active': true,
'crew_capacity': 0,
'dry_mass_kg': 4200,
'thrusters': [
{
'type': 'Draco',
'amount': 18,
'fuel_1': 'nitrogen tetroxide',
'fuel_2': 'monomethylhydrazine',
'isp': 300,
'thrust': {'kN': 0.4}
}
],
'wikipedia': 'https://en.wikipedia.org/wiki/SpaceX_Dragon',
'description':
'Dragon is a reusable spacecraft developed by SpaceX, an American private space transportation company based in Hawthorne, California. Dragon is launched into space by the SpaceX Falcon 9 two-stage-to-orbit launch vehicle. The Dragon spacecraft was originally designed for human travel, but so far has only been used to deliver cargo to the International Space Station (ISS).',
'id': '5e9d058759b1ff74a7ad5f8f'
}),
DragonVehicle(
id: '5e9d058759b1ff74a7ad5f8f',
name: 'Dragon 1',
type: 'capsule',
description:
'Dragon is a reusable spacecraft developed by SpaceX, an American private space transportation company based in Hawthorne, California. Dragon is launched into space by the SpaceX Falcon 9 two-stage-to-orbit launch vehicle. The Dragon spacecraft was originally designed for human travel, but so far has only been used to deliver cargo to the International Space Station (ISS).',
url: 'https://en.wikipedia.org/wiki/SpaceX_Dragon',
height: 7.2,
diameter: 3.7,
mass: 4200,
active: true,
firstFlight: DateTime.parse('2010-12-08'),
photos: const [
'https://i.imgur.com/9fWdwNv.jpg',
'https://live.staticflickr.com/8578/16655995541_7817565ea9_k.jpg',
'https://farm3.staticflickr.com/2815/32761844973_4b55b27d3c_b.jpg',
'https://farm9.staticflickr.com/8618/16649075267_d18cbb4342_b.jpg'
],
crew: 0,
launchMass: 6000,
returnMass: 3000,
thrusters: const [
Thruster(
model: 'Draco',
oxidizer: 'nitrogen tetroxide',
fuel: 'monomethylhydrazine',
isp: 300,
amount: 18,
thrust: 0.4,
),
],
reusable: true,
),
);
});
test('correctly returns subtitle', () {
expect(
DragonVehicle(firstFlight: DateTime(1970)).subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.first_launched',
);
expect(
DragonVehicle(firstFlight: DateTime.now().add(Duration(days: 1)))
.subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.scheduled_launch',
);
});
test('correctly returns crew info', () {
expect(
DragonVehicle(crew: 0).getCrew(MockBuildContext()),
'spacex.vehicle.capsule.description.no_people',
);
expect(
DragonVehicle(crew: 1).getCrew(MockBuildContext()),
'spacex.vehicle.capsule.description.people',
);
});
test('correctly returns crew enabled', () {
expect(
DragonVehicle(crew: 1).isCrewEnabled,
true,
);
});
test('correctly returns launch mass', () {
expect(
DragonVehicle(launchMass: 100).getLaunchMass,
'100 kg',
);
});
test('correctly returns return mass', () {
expect(
DragonVehicle(returnMass: 100).getReturnMass,
'100 kg',
);
});
test('correctly returns height', () {
expect(
DragonVehicle(height: 10).getHeight,
'10 m',
);
});
test('correctly returns diameter', () {
expect(
DragonVehicle(diameter: 10).getDiameter,
'10 m',
);
});
test('correctly returns full first flight', () {
expect(
DragonVehicle(firstFlight: DateTime(1970)).getFullFirstFlight,
'January 1, 1970',
);
expect(
DragonVehicle(firstFlight: DateTime(3000)).getFullFirstFlight,
'January 3000',
);
});
test('correctly returns photos', () {
final photos = ['one', 'two', 'three'];
expect(
DragonVehicle(photos: photos).getProfilePhoto,
photos[0],
);
expect(
DragonVehicle(photos: photos).getRandomPhoto(Random(0)),
photos[0],
);
expect(
DragonVehicle(photos: [photos[0]]).getRandomPhoto(),
photos[0],
);
});
});
group('Thruster', () {
test('is correctly generated from a JSON', () {
expect(
Thruster.fromJson(const {
'type': 'Draco',
'amount': 18,
'fuel_1': 'nitrogen tetroxide',
'fuel_2': 'monomethylhydrazine',
'isp': 300,
'thrust': {'kN': 0.4}
}),
Thruster(
model: 'Draco',
amount: 18,
oxidizer: 'nitrogen tetroxide',
fuel: 'monomethylhydrazine',
isp: 300,
thrust: 0.4,
),
);
});
test('correctly returns fuel string', () {
expect(
Thruster(fuel: 'test').getFuel,
'Test',
);
});
test('correctly returns oxidizer string', () {
expect(
Thruster(oxidizer: 'test').getOxidizer,
'Test',
);
});
test('correctly returns thruster amount', () {
expect(
Thruster(amount: 2).getAmount,
'2',
);
});
test('correctly returns thrust', () {
expect(
Thruster(thrust: 2).getThrust,
'2 kN',
);
});
test('correctly returns isp', () {
expect(
Thruster(isp: 2).getIsp,
'2 s',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/landpad_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
void main() {
group('LandpadDetails', () {
test('is correctly generated from a JSON', () {
expect(
LandpadDetails.fromJson(const {
'images': {
'large': ['image.com']
},
'name': 'OCISLY',
'full_name': 'Of Course I Still Love You',
'type': 'ASDS',
'locality': 'Port Canaveral',
'region': 'Florida',
'latitude': 28.4104,
'longitude': -80.6188,
'landing_attempts': 36,
'landing_successes': 30,
'wikipedia':
'https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship',
'details':
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
'status': 'active',
'id': '5e9e3032383ecb6bb234e7ca'
}),
LandpadDetails(
name: 'OCISLY',
fullName: 'Of Course I Still Love You',
type: 'ASDS',
locality: 'Port Canaveral',
region: 'Florida',
latitude: 28.4104,
longitude: -80.6188,
landingAttempts: 36,
landingSuccesses: 30,
wikipediaUrl:
'https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship',
details:
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
status: 'active',
id: '5e9e3032383ecb6bb234e7ca',
),
);
});
test('correctly returns coordenates', () {
expect(
LandpadDetails(latitude: 28, longitude: -80).coordinates,
LatLng(28, -80),
);
});
test('correctly returns status', () {
expect(
LandpadDetails(status: 'test').getStatus,
'Test',
);
});
test('correctly returns string coordenates', () {
expect(
LandpadDetails(latitude: 28, longitude: -80).getCoordinates,
'28.000, -80.000',
);
});
test('correctly returns successful landings', () {
expect(
LandpadDetails(landingAttempts: 10, landingSuccesses: 5)
.getSuccessfulLandings,
'5/10',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/achievement_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Achievement', () {
test('is correctly generated from a JSON', () {
expect(
Achievement.fromJson(const {
"links": {
"article":
"http://www.spacex.com/news/2013/02/11/flight-4-launch-update-0"
},
"title": "Falcon reaches Earth orbit",
"event_date_utc": "2008-09-28T23:15:00Z",
"event_date_unix": 1222643700,
"details":
"Falcon 1 becomes the first privately developed liquid-fuel rocket to reach Earth orbit.",
"id": "5f6fb2cfdcfdf403df37971e"
}),
Achievement(
name: 'Falcon reaches Earth orbit',
date: DateTime.parse('2008-09-28T23:15:00Z'),
details:
'Falcon 1 becomes the first privately developed liquid-fuel rocket to reach Earth orbit.',
id: '5f6fb2cfdcfdf403df37971e',
url:
'http://www.spacex.com/news/2013/02/11/flight-4-launch-update-0'),
);
});
test('correctly returns parsed date', () {
expect(
Achievement(date: DateTime.parse("2008-09-28T23:15:00Z")).getDate,
'September 28, 2008',
);
});
test('correctly checks link', () {
expect(
Achievement(url: 'google.es').hasLink,
true,
);
expect(
Achievement().hasLink,
false,
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/launchpad_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
void main() {
group('LaunchpadDetails', () {
test('is correctly generated from a JSON', () {
expect(
LaunchpadDetails.fromJson(const {
'images': {
'large': ['image.com']
},
"name": "Kwajalein Atoll",
"full_name": "Kwajalein Atoll Omelek Island",
"locality": "Omelek Island",
"region": "Marshall Islands",
"latitude": 9.0477206,
"longitude": 167.7431292,
"launch_attempts": 5,
"launch_successes": 2,
"details":
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
"id": "5e9e4502f5090995de566f86"
}),
LaunchpadDetails(
name: 'Kwajalein Atoll',
fullName: 'Kwajalein Atoll Omelek Island',
locality: 'Omelek Island',
region: 'Marshall Islands',
latitude: 9.0477206,
longitude: 167.7431292,
launchAttempts: 5,
launchSuccesses: 2,
details:
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
id: '5e9e4502f5090995de566f86',
),
);
});
test('correctly returns coordenates', () {
expect(
LaunchpadDetails(latitude: 28, longitude: -80).coordinates,
LatLng(28, -80),
);
});
test('correctly returns status', () {
expect(
LaunchpadDetails(status: 'test').getStatus,
'Test',
);
});
test('correctly returns string coordenates', () {
expect(
LaunchpadDetails(latitude: 28, longitude: -80).getCoordinates,
'28.000, -80.000',
);
});
test('correctly returns successful landings', () {
expect(
LaunchpadDetails(launchAttempts: 10, launchSuccesses: 5)
.getSuccessfulLaunches,
'5/10',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/capsule_details_test.dart | import 'package:cherry/models/index.dart';
import 'package:intl/intl.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('CapsuleDetails', () {
test('is correctly generated from a JSON', () {
expect(
CapsuleDetails.fromJson(const {
'reuse_count': 1,
'water_landings': 1,
'last_update': 'descripction',
'launches': [
{
'flight_number': 10,
'name': 'CRS-2',
"date_utc": "2015-06-28T14:21:00.000Z",
'id': '5eb87ce1ffd86e000604b333'
}
],
'serial': 'C104',
'status': 'unknown',
"type": "Dragon 1.0",
'id': '5e9e2c5bf359189ef23b2667'
}),
CapsuleDetails(
reuseCount: 1,
splashings: 1,
lastUpdate: 'descripction',
launches: [
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87ce1ffd86e000604b333',
)
],
serial: 'C104',
status: 'unknown',
type: 'Dragon 1.0',
id: '5e9e2c5bf359189ef23b2667',
),
);
});
test('correctly returns first launch data', () {
expect(
CapsuleDetails(launches: const []).getFirstLaunched(MockBuildContext()),
'spacex.other.unknown',
);
expect(
CapsuleDetails(
launches: [LaunchDetails(date: DateTime.now())],
).getFirstLaunched(MockBuildContext()),
DateFormat.yMMMMd().format(DateTime.now().toLocal()),
);
});
test('correctly returns details', () {
expect(
CapsuleDetails().getDetails(MockBuildContext()),
'spacex.dialog.vehicle.no_description_capsule',
);
expect(
CapsuleDetails(lastUpdate: 'Lorem').getDetails(MockBuildContext()),
'Lorem',
);
});
test('correctly returns parsed status', () {
expect(
CapsuleDetails(status: 'test').getStatus,
'Test',
);
});
test('correctly returns splashing number', () {
expect(
CapsuleDetails(splashings: 2).getSplashings,
'2',
);
});
test('correctly returns launch number', () {
expect(
CapsuleDetails(launches: const [
LaunchDetails(),
LaunchDetails(),
]).getLaunches,
'2',
);
});
test('correctly check mission number', () {
expect(
CapsuleDetails(launches: const []).hasMissions,
false,
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/rocket_vehicle_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('RocketVehicle', () {
test('is correctly generated from a JSON', () {
expect(
RocketVehicle.fromJson(const {
'height': {'meters': 22.25},
'diameter': {'meters': 1.68},
'mass': {'kg': 30146},
'first_stage': {
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 44.3
},
'second_stage': {
'thrust': {'kN': 31},
'payloads': {
'composite_fairing': {
'height': {'meters': 3.5},
'diameter': {'meters': 1.5}
}
},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 3.38
},
'engines': {
'isp': {'sea_level': 267, 'vacuum': 304},
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'type': 'merlin',
'version': '1C',
'propellant_1': 'liquid oxygen',
'propellant_2': 'RP-1 kerosene',
'thrust_to_weight': 96
},
'payload_weights': [
{'id': 'leo', 'name': 'Low Earth Orbit', 'kg': 450}
],
'flickr_images': [
'https://imgur.com/DaCfMsj.jpg',
'https://imgur.com/azYafd8.jpg'
],
'name': 'Falcon 1',
'type': 'rocket',
'active': false,
'stages': 2,
'boosters': 0,
'cost_per_launch': 6700000,
'success_rate_pct': 40,
'first_flight': '2006-03-24',
'wikipedia': 'https://en.wikipedia.org/wiki/Falcon_1',
'description':
'The Falcon 1 was an expendable launch system privately developed and manufactured by SpaceX during 2006-2009. On 28 September 2008, Falcon 1 became the first privately-developed liquid-fuel launch vehicle to go into orbit around the Earth.',
'id': '5e9d0d95eda69955f709d1eb'
}),
RocketVehicle(
id: '5e9d0d95eda69955f709d1eb',
name: 'Falcon 1',
type: 'rocket',
description:
'The Falcon 1 was an expendable launch system privately developed and manufactured by SpaceX during 2006-2009. On 28 September 2008, Falcon 1 became the first privately-developed liquid-fuel launch vehicle to go into orbit around the Earth.',
url: 'https://en.wikipedia.org/wiki/Falcon_1',
height: 22.25,
diameter: 1.68,
mass: 30146,
active: false,
firstFlight: DateTime.parse('2006-03-24'),
photos: const [
'https://imgur.com/DaCfMsj.jpg',
'https://imgur.com/azYafd8.jpg'
],
stages: 2,
launchCost: 6700000,
successRate: 40,
payloadWeights: const [
PayloadWeight('Low Earth Orbit', 450),
],
engine: Engine(
thrustSea: 420,
thrustVacuum: 480,
thrustToWeight: 96,
ispSea: 267,
ispVacuum: 304,
name: 'merlin 1C',
fuel: 'RP-1 kerosene',
oxidizer: 'liquid oxygen',
),
firstStage: Stage(
reusable: false,
engines: 1,
fuelAmount: 44.3,
thrust: 420,
),
secondStage: Stage(
reusable: false,
engines: 1,
fuelAmount: 3.38,
thrust: 31,
),
fairingDimensions: const [3.5, 1.5],
),
);
});
test('correctly returns launch cost', () {
expect(
RocketVehicle(launchCost: 10).getLaunchCost,
'\$10',
);
});
test('correctly returns details', () {
expect(
RocketVehicle(firstFlight: DateTime(1970)).subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.first_launched',
);
expect(
RocketVehicle(firstFlight: DateTime.now().add(Duration(minutes: 10)))
.subtitle(MockBuildContext()),
'spacex.vehicle.subtitle.scheduled_launch',
);
});
test('correctly returns success rate', () {
expect(
RocketVehicle(firstFlight: DateTime(1970), successRate: 90)
.getSuccessRate(MockBuildContext()),
'90%',
);
expect(
RocketVehicle(firstFlight: DateTime.now().add(Duration(minutes: 10)))
.getSuccessRate(MockBuildContext()),
'spacex.other.no_data',
);
});
test('correctly returns fairing height', () {
expect(
RocketVehicle(fairingDimensions: const [null, null])
.fairingHeight(MockBuildContext()),
'spacex.other.unknown',
);
expect(
RocketVehicle(fairingDimensions: const [10, null])
.fairingHeight(MockBuildContext()),
'10 m',
);
});
test('correctly returns fairing diameter', () {
expect(
RocketVehicle(fairingDimensions: const [null, null])
.fairingDiameter(MockBuildContext()),
'spacex.other.unknown',
);
expect(
RocketVehicle(fairingDimensions: const [null, 10])
.fairingDiameter(MockBuildContext()),
'10 m',
);
});
test('correctly returns stages info', () {
expect(
RocketVehicle(stages: 2).getStages(MockBuildContext()),
'spacex.vehicle.rocket.specifications.stages',
);
});
});
group('Engine', () {
test('is correctly generated from a JSON', () {
expect(
Engine.fromJson(const {
'isp': {'sea_level': 267, 'vacuum': 304},
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'type': 'merlin',
'version': '1C',
'propellant_1': 'liquid oxygen',
'propellant_2': 'RP-1 kerosene',
'thrust_to_weight': 96
}),
Engine(
thrustSea: 420,
thrustVacuum: 480,
thrustToWeight: 96,
ispSea: 267,
ispVacuum: 304,
name: 'merlin 1C',
fuel: 'RP-1 kerosene',
oxidizer: 'liquid oxygen',
),
);
});
test('correctly returns fuel string', () {
expect(
Engine(fuel: 'test').getFuel,
'Test',
);
});
test('correctly returns oxidizer string', () {
expect(
Engine(oxidizer: 'test').getOxidizer,
'Test',
);
});
test('correctly returns sea thrust', () {
expect(
Engine(thrustSea: 100).getThrustSea,
'100 kN',
);
});
test('correctly returns vacuum thrust', () {
expect(
Engine(thrustVacuum: 100).getThrustVacuum,
'100 kN',
);
});
test('correctly returns sea isp', () {
expect(
Engine(ispSea: 100).getIspSea,
'100 s',
);
});
test('correctly returns vacuum isp', () {
expect(
Engine(ispVacuum: 100).getIspVacuum,
'100 s',
);
});
test('correctly returns name', () {
expect(
Engine(name: 'test').getName,
'Test',
);
});
test('correctly returns thurst to weight', () {
expect(
Engine().getThrustToWeight(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Engine(thrustToWeight: 100).getThrustToWeight(MockBuildContext()),
'100',
);
});
});
group('PayloadWeight', () {
test('is correctly generated from a JSON', () {
expect(
PayloadWeight.fromJson(
const {
'id': 'leo',
'name': 'Low Earth Orbit',
'kg': 450,
},
),
PayloadWeight(
'Low Earth Orbit',
450,
),
);
});
test('correctly returns mass', () {
expect(
PayloadWeight('test', 100).getMass,
'100 kg',
);
});
});
group('Stage', () {
test('First stage is correctly generated from a JSON', () {
expect(
Stage.fromJson(const {
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 44.3
}),
Stage(
reusable: false,
engines: 1,
fuelAmount: 44.3,
thrust: 420,
),
);
});
test('Second stage is correctly generated from a JSON', () {
expect(
Stage.fromJson(const {
'thrust': {'kN': 31},
'payloads': {
'composite_fairing': {
'height': {'meters': 3.5},
'diameter': {'meters': 1.5}
}
},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 3.38
}),
Stage(
reusable: false,
engines: 1,
fuelAmount: 3.38,
thrust: 31,
),
);
});
test('correctly returns thrust', () {
expect(
Stage(thrust: 100).getThrust,
'100 kN',
);
});
test('correctly returns engine info', () {
expect(
Stage(engines: 1).getEngines(MockBuildContext()),
'spacex.vehicle.rocket.stage.engine_number',
);
expect(
Stage(engines: 2).getEngines(MockBuildContext()),
'spacex.vehicle.rocket.stage.engines_number',
);
});
test('correctly returns fuel amount', () {
expect(
Stage(fuelAmount: 100).getFuelAmount(MockBuildContext()),
'spacex.vehicle.rocket.stage.fuel_amount_tons',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/payload_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'mock_context.dart';
void main() {
group('Payload', () {
test('is correctly generated from a JSON', () {
expect(
Payload.fromJson(const {
"dragon": {
"capsule": {
"reuse_count": 1,
"water_landings": 1,
"last_update": "descripction",
"launches": [
{
"flight_number": 10,
"name": "CRS-2",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87ce1ffd86e000604b333"
}
],
"serial": "C104",
"status": "unknown",
"type": "Dragon 1.0",
"id": "5e9e2c5bf359189ef23b2667"
}
},
"name": "FalconSAT-2",
"reused": true,
"customers": ["DARPA"],
"nationalities": ["United States"],
"manufacturers": ["SSTL"],
"mass_kg": 20,
"orbit": "LEO",
"periapsis_km": 400,
"apoapsis_km": 500,
"inclination_deg": 39,
"period_min": 90.0,
"id": "5eb0e4b5b6c3bb0006eeb1e1"
}),
Payload(
capsule: CapsuleDetails(
reuseCount: 1,
splashings: 1,
lastUpdate: 'descripction',
launches: [
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87ce1ffd86e000604b333',
)
],
serial: 'C104',
status: 'unknown',
type: 'Dragon 1.0',
id: '5e9e2c5bf359189ef23b2667',
),
name: 'FalconSAT-2',
reused: true,
customer: 'DARPA',
nationality: 'United States',
manufacturer: 'SSTL',
mass: 20,
orbit: 'LEO',
periapsis: 400,
apoapsis: 500,
inclination: 39,
period: 90.0,
id: '5eb0e4b5b6c3bb0006eeb1e1',
),
);
});
test('correctly checks name', () {
expect(
Payload().getName(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(name: 'Lorem').getName(MockBuildContext()),
'Lorem',
);
});
test('correctly checks customer', () {
expect(
Payload().getCustomer(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(customer: 'Lorem').getCustomer(MockBuildContext()),
'Lorem',
);
});
test('correctly checks nationality', () {
expect(
Payload().getNationality(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(nationality: 'Lorem').getNationality(MockBuildContext()),
'Lorem',
);
});
test('correctly checks manufacturer', () {
expect(
Payload().getManufacturer(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(manufacturer: 'Lorem').getManufacturer(MockBuildContext()),
'Lorem',
);
});
test('correctly checks orbit', () {
expect(
Payload().getOrbit(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(orbit: 'Lorem').getOrbit(MockBuildContext()),
'Lorem',
);
});
test('correctly checks mass', () {
expect(
Payload().getMass(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(mass: 100).getMass(MockBuildContext()),
'100 kg',
);
});
test('correctly checks periapsis', () {
expect(
Payload().getPeriapsis(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(periapsis: 100).getPeriapsis(MockBuildContext()),
'100 km',
);
});
test('correctly checks apoapsis', () {
expect(
Payload().getApoapsis(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(apoapsis: 100).getApoapsis(MockBuildContext()),
'100 km',
);
});
test('correctly checks inclination', () {
expect(
Payload().getInclination(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(inclination: 100).getInclination(MockBuildContext()),
'100°',
);
});
test('correctly checks period', () {
expect(
Payload().getPeriod(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Payload(period: 100).getPeriod(MockBuildContext()),
'100 min',
);
});
test('correctly checks for NASA payload', () {
expect(
Payload(customer: 'NASA (CCtCap)').isNasaPayload,
true,
);
expect(
Payload(customer: 'NASA (CRS)').isNasaPayload,
true,
);
expect(
Payload(customer: 'NASA(COTS)').isNasaPayload,
true,
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/launch_details_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LaunchDetails', () {
test('is correctly generated from a JSON with date', () {
expect(
LaunchDetails.fromJson(const {
'flight_number': 10,
'name': 'CRS-2',
'date_utc': '2015-06-28T14:21:00.000Z',
'id': '5eb87ce1ffd86e000604b333'
}),
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87ce1ffd86e000604b333',
),
);
});
test('is correctly generated from a JSON with date', () {
expect(
LaunchDetails.fromJson(const {
'flight_number': 10,
'name': 'CRS-2',
'id': '5eb87ce1ffd86e000604b333'
}),
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
id: '5eb87ce1ffd86e000604b333',
),
);
});
test('correctly returns local date', () {
final date = DateTime.now();
expect(
LaunchDetails(date: date).localDate,
date,
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/core_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart';
import 'mock_context.dart';
void main() {
group('Core', () {
test('is correctly generated from a JSON', () {
expect(
Core.fromJson(const {
"core": {
"block": 5,
"reuse_count": 0,
"rtls_attempts": 0,
"rtls_landings": 0,
"asds_attempts": 0,
"asds_landings": 0,
"last_update":
"Engine failure at T+33 seconds resulted in loss of vehicle",
"launches": [
{
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87cd9ffd86e000604b32a"
}
],
"serial": "Merlin1A",
"status": "lost",
"id": "5e9e289df35918033d3b2623"
},
"gridfins": false,
"legs": false,
"reused": false,
"landing_attempt": false,
"landing_success": false,
"landpad": {
'images': {
'large': ['image.com']
},
"name": "OCISLY",
"full_name": "Of Course I Still Love You",
"type": "ASDS",
"locality": "Port Canaveral",
"region": "Florida",
"latitude": 28.4104,
"longitude": -80.6188,
"landing_attempts": 36,
"landing_successes": 30,
"wikipedia":
"https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship",
"details":
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
"status": "active",
"id": "5e9e3032383ecb6bb234e7ca"
}
}),
Core(
block: 5,
reuseCount: 0,
rtlsAttempts: 0,
rtlsLandings: 0,
asdsAttempts: 0,
asdsLandings: 0,
lastUpdate:
'Engine failure at T+33 seconds resulted in loss of vehicle',
launches: [
LaunchDetails(
flightNumber: 1,
name: 'FalconSat',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87cd9ffd86e000604b32a',
),
],
serial: 'Merlin1A',
status: 'lost',
id: '5e9e289df35918033d3b2623',
hasGridfins: false,
hasLegs: false,
reused: false,
landingAttempt: false,
landingSuccess: false,
landpad: LandpadDetails(
name: 'OCISLY',
fullName: 'Of Course I Still Love You',
type: 'ASDS',
locality: 'Port Canaveral',
region: 'Florida',
latitude: 28.4104,
longitude: -80.6188,
landingAttempts: 36,
landingSuccesses: 30,
wikipediaUrl:
'https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship',
details:
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
status: 'active',
id: '5e9e3032383ecb6bb234e7ca',
),
),
);
});
test('correctly returns first launch data', () {
expect(
Core(launches: const []).getFirstLaunched(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Core(
launches: [LaunchDetails(date: DateTime.now())],
).getFirstLaunched(MockBuildContext()),
DateFormat.yMMMMd().format(DateTime.now().toLocal()),
);
});
test('correctly returns details', () {
expect(
Core().getDetails(MockBuildContext()),
'spacex.dialog.vehicle.no_description_core',
);
expect(
Core(lastUpdate: 'Lorem').getDetails(MockBuildContext()),
'Lorem',
);
});
test('correctly returns block', () {
expect(
Core().getBlock(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Core(block: 5).getBlock(MockBuildContext()),
'spacex.other.block',
);
});
test('correctly returns status', () {
expect(
Core(status: 'test').getStatus,
'Test',
);
});
test('correctly returns launch number', () {
expect(
Core(launches: const [
LaunchDetails(),
LaunchDetails(),
]).getLaunches,
'2',
);
});
test('correctly check mission number', () {
expect(
Core(launches: const []).hasMissions,
false,
);
});
test('correctly returns RTLS landings', () {
expect(
Core(rtlsAttempts: 10, rtlsLandings: 5).getRtlsLandings,
'5/10',
);
});
test('correctly returns ASDS landings', () {
expect(
Core(asdsAttempts: 10, asdsLandings: 5).getAsdsLandings,
'5/10',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/mock_context.dart | import 'package:flutter/material.dart';
import 'package:mockito/mockito.dart';
class MockBuildContext extends Mock implements BuildContext {}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/models/launch_test.dart | import 'package:cherry/models/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart';
import 'mock_context.dart';
void main() {
group('Launch', () {
test('is correctly generated from a JSON', () {
expect(
Launch.fromJson(const {
"fairings": {
"reused": true,
"recovery_attempt": true,
"recovered": true,
"ships": [
{"name": "GO Ms Tree", "id": "5ea6ed2e080df4000697c908"}
]
},
"links": {
"patch": {
"small": "https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png"
},
"reddit": {
"campaign": "http",
},
"flickr": {
"original": [
"https://farm8.staticflickr.com/7615/16670240949_8d43db0e36_o.jpg",
"https://farm9.staticflickr.com/8597/16856369125_e97cd30ef7_o.jpg",
"https://farm8.staticflickr.com/7586/16166732954_9338dc859c_o.jpg",
"https://farm8.staticflickr.com/7603/16855223522_462da54e84_o.jpg",
"https://farm8.staticflickr.com/7618/16234010894_e1210ec300_o.jpg",
"https://farm8.staticflickr.com/7617/16855338881_69542a2fa9_o.jpg"
]
},
"presskit": "http",
"webcast": "https://www.youtube.com/watch?v=0a_00nJ_Y88"
},
"static_fire_date_utc": "2006-03-17T00:00:00.000Z",
"tbd": false,
"net": false,
"window": 0,
"rocket": {
"name": "Falcon 1",
"id": "5e9d0d95eda69955f709d1eb",
},
"success": false,
"failures": [
{
"time": 139,
"altitude": 40,
"reason":
"helium tank overpressure lead to the second stage LOX tank explosion"
}
],
"details": "Engine failure at 33 seconds and loss of vehicle",
"payloads": [
{
"dragon": {
"capsule": {
"reuse_count": 1,
"water_landings": 1,
"last_update": "descripction",
"launches": [
{
"flight_number": 10,
"name": "CRS-2",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87ce1ffd86e000604b333"
}
],
"serial": "C104",
"status": "unknown",
"type": "Dragon 1.0",
"id": "5e9e2c5bf359189ef23b2667"
}
},
"name": "FalconSAT-2",
"reused": true,
"customers": ["DARPA"],
"nationalities": ["United States"],
"manufacturers": ["SSTL"],
"mass_kg": 20,
"orbit": "LEO",
"periapsis_km": 400,
"apoapsis_km": 500,
"inclination_deg": 39,
"period_min": 90.0,
"id": "5eb0e4b5b6c3bb0006eeb1e1"
}
],
"launchpad": {
'images': {
'large': ['image.com']
},
"name": "Kwajalein Atoll",
"full_name": "Kwajalein Atoll Omelek Island",
"locality": "Omelek Island",
"region": "Marshall Islands",
"latitude": 9.0477206,
"longitude": 167.7431292,
"launch_attempts": 5,
"launch_successes": 2,
"details":
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
"id": "5e9e4502f5090995de566f86"
},
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2006-03-24T22:30:00.000Z",
"date_precision": "hour",
"upcoming": false,
"cores": [
{
"core": {
"block": 5,
"reuse_count": 0,
"rtls_attempts": 0,
"rtls_landings": 0,
"asds_attempts": 0,
"asds_landings": 0,
"last_update":
"Engine failure at T+33 seconds resulted in loss of vehicle",
"launches": [
{
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87cd9ffd86e000604b32a"
}
],
"serial": "Merlin1A",
"status": "lost",
"id": "5e9e289df35918033d3b2623"
},
"gridfins": false,
"legs": false,
"reused": false,
"landing_attempt": false,
"landing_success": false,
"landpad": {
'images': {
'large': ['image.com']
},
"name": "OCISLY",
"full_name": "Of Course I Still Love You",
"type": "ASDS",
"locality": "Port Canaveral",
"region": "Florida",
"latitude": 28.4104,
"longitude": -80.6188,
"landing_attempts": 36,
"landing_successes": 30,
"landing_type": "ASDS",
"wikipedia":
"https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship",
"details":
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
"status": "active",
"id": "5e9e3032383ecb6bb234e7ca"
}
}
],
"id": "5eb87cd9ffd86e000604b32a"
}),
Launch(
patchUrl: 'https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png',
links: const [
'https://www.youtube.com/watch?v=0a_00nJ_Y88',
'http',
'http',
],
photos: const [
"https://farm8.staticflickr.com/7615/16670240949_8d43db0e36_o.jpg",
"https://farm9.staticflickr.com/8597/16856369125_e97cd30ef7_o.jpg",
"https://farm8.staticflickr.com/7586/16166732954_9338dc859c_o.jpg",
"https://farm8.staticflickr.com/7603/16855223522_462da54e84_o.jpg",
"https://farm8.staticflickr.com/7618/16234010894_e1210ec300_o.jpg",
"https://farm8.staticflickr.com/7617/16855338881_69542a2fa9_o.jpg"
],
staticFireDate: DateTime.tryParse('2006-03-17T00:00:00.000Z'),
launchWindow: 0,
success: false,
failure: FailureDetails(
altitude: 40,
time: 139,
reason:
'helium tank overpressure lead to the second stage LOX tank explosion',
),
details: 'Engine failure at 33 seconds and loss of vehicle',
rocket: RocketDetails(
fairings: FairingsDetails(
reused: true,
recoveryAttempt: true,
recovered: true,
),
cores: [
Core(
block: 5,
reuseCount: 0,
rtlsAttempts: 0,
rtlsLandings: 0,
asdsAttempts: 0,
asdsLandings: 0,
lastUpdate:
'Engine failure at T+33 seconds resulted in loss of vehicle',
launches: [
LaunchDetails(
flightNumber: 1,
name: 'FalconSat',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87cd9ffd86e000604b32a',
),
],
serial: 'Merlin1A',
status: 'lost',
id: '5e9e289df35918033d3b2623',
hasGridfins: false,
hasLegs: false,
reused: false,
landingAttempt: false,
landingSuccess: false,
landpad: LandpadDetails(
name: 'OCISLY',
fullName: 'Of Course I Still Love You',
type: 'ASDS',
locality: 'Port Canaveral',
region: 'Florida',
latitude: 28.4104,
longitude: -80.6188,
landingAttempts: 36,
landingSuccesses: 30,
wikipediaUrl:
'https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship',
details:
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
status: 'active',
id: '5e9e3032383ecb6bb234e7ca',
),
),
],
payloads: [
Payload(
capsule: CapsuleDetails(
reuseCount: 1,
splashings: 1,
lastUpdate: 'descripction',
launches: [
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87ce1ffd86e000604b333',
)
],
serial: 'C104',
status: 'unknown',
type: 'Dragon 1.0',
id: '5e9e2c5bf359189ef23b2667',
),
name: 'FalconSAT-2',
reused: true,
customer: 'DARPA',
nationality: 'United States',
manufacturer: 'SSTL',
mass: 20,
orbit: 'LEO',
periapsis: 400,
apoapsis: 500,
inclination: 39,
period: 90.0,
id: '5eb0e4b5b6c3bb0006eeb1e1',
),
],
name: 'Falcon 1',
id: '5e9d0d95eda69955f709d1eb',
),
launchpad: LaunchpadDetails(
name: 'Kwajalein Atoll',
fullName: 'Kwajalein Atoll Omelek Island',
locality: 'Omelek Island',
region: 'Marshall Islands',
latitude: 9.0477206,
longitude: 167.7431292,
launchAttempts: 5,
launchSuccesses: 2,
details:
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
id: '5e9e4502f5090995de566f86',
),
flightNumber: 1,
name: 'FalconSat',
launchDate: DateTime.tryParse('2006-03-24T22:30:00.000Z'),
datePrecision: 'hour',
upcoming: false,
id: '5eb87cd9ffd86e000604b32a',
),
);
});
test('correctly returns launch window string', () {
expect(
Launch().getLaunchWindow(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Launch(launchWindow: 0).getLaunchWindow(MockBuildContext()),
'spacex.launch.page.rocket.instantaneous_window',
);
expect(
Launch(launchWindow: 59).getLaunchWindow(MockBuildContext()),
'59 s',
);
expect(
Launch(launchWindow: 60).getLaunchWindow(MockBuildContext()),
'1 min',
);
expect(
Launch(launchWindow: 3599).getLaunchWindow(MockBuildContext()),
'59 min',
);
expect(
Launch(launchWindow: 3600).getLaunchWindow(MockBuildContext()),
'1 h',
);
expect(
Launch(launchWindow: 5000).getLaunchWindow(MockBuildContext()),
'1h 23min',
);
});
test('correctly returns launch details', () {
expect(
Launch().getDetails(MockBuildContext()),
'spacex.launch.page.no_description',
);
expect(
Launch(details: 'Lorem').getDetails(MockBuildContext()),
'Lorem',
);
});
test('correctly returns launch date info', () {
expect(
Launch(
launchDate: DateTime(1970),
datePrecision: 'hour',
).getLaunchDate(MockBuildContext()),
'spacex.other.date.time',
);
expect(
Launch(
launchDate: DateTime(1970),
datePrecision: 'day',
).getLaunchDate(MockBuildContext()),
'spacex.other.date.upcoming',
);
});
test('correctly returns static fire details', () {
expect(
Launch().getStaticFireDate(MockBuildContext()),
'spacex.other.unknown',
);
expect(
Launch(staticFireDate: DateTime.now())
.getStaticFireDate(MockBuildContext()),
DateFormat.yMMMMd().format(DateTime.now()),
);
});
test('link menu works great', () {
expect(
Launch.getMenuIndex('spacex.launch.menu.reddit'),
1,
);
expect(
Launch.getMenuIndex('spacex.launch.menu.press_kit'),
2,
);
expect(
Launch(links: const ['google.com', 'google.es'])
.isUrlEnabled('spacex.launch.menu.reddit'),
true,
);
expect(
Launch(links: const ['google.com', null])
.isUrlEnabled('spacex.launch.menu.reddit'),
false,
);
expect(
Launch(links: const ['google.com', 'google.es'])
.getUrl('spacex.launch.menu.reddit'),
'google.es',
);
});
test('correctly compares with other launch', () {
expect(
Launch(flightNumber: 1).compareTo(Launch(flightNumber: 2)),
-1,
);
expect(
Launch(flightNumber: 10).compareTo(Launch(flightNumber: 2)),
1,
);
expect(
Launch(flightNumber: 1).compareTo(Launch(flightNumber: 1)),
0,
);
});
test('correctly returns local launch date', () {
final date = DateTime.now();
expect(
Launch(launchDate: date).localLaunchDate,
date,
);
});
test('correctly returns local static fire date', () {
final date = DateTime.now();
expect(
Launch(staticFireDate: date).localStaticFireDate,
date,
);
});
test('correctly returns formatted flight number', () {
expect(
Launch(flightNumber: 1).getNumber,
'#01',
);
});
test('correctly checks for path image', () {
expect(
Launch(patchUrl: 'google.es').hasPatch,
true,
);
expect(
Launch().hasPatch,
false,
);
});
test('correctly checks for video', () {
expect(
Launch(links: const ['google.es']).hasVideo,
true,
);
expect(
Launch(links: const [null]).hasVideo,
false,
);
});
test('correctly returns video', () {
expect(
Launch(links: const ['google.es']).getVideo,
'google.es',
);
});
test('correctly checks for tentative hour', () {
expect(
Launch(datePrecision: 'hour').tentativeTime,
false,
);
expect(
Launch(datePrecision: '').tentativeTime,
true,
);
});
test('correctly returns tentative date', () {
final date = DateTime(1970);
expect(
Launch(datePrecision: 'hour', launchDate: date).getTentativeDate,
'January 1, 1970',
);
expect(
Launch(datePrecision: 'day', launchDate: date).getTentativeDate,
'January 1, 1970',
);
expect(
Launch(datePrecision: 'month', launchDate: date).getTentativeDate,
'January 1970',
);
expect(
Launch(datePrecision: 'quarter', launchDate: date).getTentativeDate,
'Q1 1970',
);
expect(
Launch(datePrecision: 'half', launchDate: date).getTentativeDate,
'H1 1970',
);
expect(
Launch(datePrecision: 'year', launchDate: date).getTentativeDate,
'1970',
);
expect(
Launch(datePrecision: '', launchDate: date).getTentativeDate,
'date error',
);
});
test('correctly returns short tentative time', () {
expect(
Launch(launchDate: DateTime(1970)).getShortTentativeTime,
'00:00',
);
});
test('correctly returns short tentative time with time zone', () {
final date = DateTime(1970);
expect(
Launch(launchDate: date).getTentativeTime,
'00:00 ${date.timeZoneName}',
);
});
test('correctly checks for too tentative launch date', () {
expect(
Launch(datePrecision: 'hour').isDateTooTentative,
false,
);
expect(
Launch(datePrecision: 'day').isDateTooTentative,
false,
);
expect(
Launch(datePrecision: '').isDateTooTentative,
true,
);
});
test('correctly returns launch year', () {
expect(
Launch(launchDate: DateTime(1970)).year,
'1970',
);
});
test('correctly checks for photos', () {
expect(
Launch(photos: const []).hasPhotos,
false,
);
expect(
Launch(photos: const ['']).hasPhotos,
true,
);
});
test('correctly checks for static fire occurrence', () {
expect(
Launch(
staticFireDate: DateTime(1970),
upcoming: false,
).avoidedStaticFire,
false,
);
expect(
Launch(
staticFireDate: DateTime(1970),
upcoming: true,
).avoidedStaticFire,
false,
);
expect(
Launch(
upcoming: false,
).avoidedStaticFire,
true,
);
expect(
Launch(
upcoming: true,
).avoidedStaticFire,
false,
);
});
});
group('RocketDetails', () {
test('is correctly generated from a JSON', () {
expect(
RocketDetails.fromJson(const {
"fairings": {
"reused": true,
"recovery_attempt": true,
"recovered": true,
"ships": [
{"name": "GO Ms Tree", "id": "5ea6ed2e080df4000697c908"}
]
},
"links": {
"patch": {
"small": "https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png"
},
"reddit": {
"campaign": "http",
},
"flickr": {
"original": [
"https://farm8.staticflickr.com/7615/16670240949_8d43db0e36_o.jpg",
"https://farm9.staticflickr.com/8597/16856369125_e97cd30ef7_o.jpg",
"https://farm8.staticflickr.com/7586/16166732954_9338dc859c_o.jpg",
"https://farm8.staticflickr.com/7603/16855223522_462da54e84_o.jpg",
"https://farm8.staticflickr.com/7618/16234010894_e1210ec300_o.jpg",
"https://farm8.staticflickr.com/7617/16855338881_69542a2fa9_o.jpg"
]
},
"presskit": "http",
"webcast": "https://www.youtube.com/watch?v=0a_00nJ_Y88"
},
"static_fire_date_utc": "2006-03-17T00:00:00.000Z",
"tbd": false,
"net": false,
"window": 0,
"rocket": {
"name": "Falcon 1",
"id": "5e9d0d95eda69955f709d1eb",
},
"success": false,
"failures": {
"time": 139,
"altitude": 40,
"reason":
"helium tank overpressure lead to the second stage LOX tank explosion"
},
"details": "Engine failure at 33 seconds and loss of vehicle",
"payloads": [
{
"dragon": {
"capsule": {
"reuse_count": 1,
"water_landings": 1,
"last_update": "descripction",
"launches": [
{
"flight_number": 10,
"name": "CRS-2",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87ce1ffd86e000604b333"
}
],
"serial": "C104",
"status": "unknown",
"type": "Dragon 1.0",
"id": "5e9e2c5bf359189ef23b2667"
}
},
"name": "FalconSAT-2",
"reused": true,
"customers": ["DARPA"],
"nationalities": ["United States"],
"manufacturers": ["SSTL"],
"mass_kg": 20,
"orbit": "LEO",
"periapsis_km": 400,
"apoapsis_km": 500,
"inclination_deg": 39,
"period_min": 90.0,
"id": "5eb0e4b5b6c3bb0006eeb1e1"
}
],
"launchpad": {
'images': {
'large': ['image.com']
},
"name": "Kwajalein Atoll",
"full_name": "Kwajalein Atoll Omelek Island",
"locality": "Omelek Island",
"region": "Marshall Islands",
"latitude": 9.0477206,
"longitude": 167.7431292,
"launch_attempts": 5,
"launch_successes": 2,
"details":
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
"id": "5e9e4502f5090995de566f86"
},
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2006-03-24T22:30:00.000Z",
"date_precision": "hour",
"upcoming": false,
"cores": [
{
"core": {
"block": 5,
"reuse_count": 0,
"rtls_attempts": 0,
"rtls_landings": 0,
"asds_attempts": 0,
"asds_landings": 0,
"last_update":
"Engine failure at T+33 seconds resulted in loss of vehicle",
"launches": [
{
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87cd9ffd86e000604b32a"
}
],
"serial": "Merlin1A",
"status": "lost",
"id": "5e9e289df35918033d3b2623"
},
"gridfins": false,
"legs": false,
"reused": false,
"landing_attempt": false,
"landing_success": false,
"landpad": {
'images': {
'large': ['image.com']
},
"name": "OCISLY",
"full_name": "Of Course I Still Love You",
"type": "ASDS",
"locality": "Port Canaveral",
"region": "Florida",
"latitude": 28.4104,
"longitude": -80.6188,
"landing_attempts": 36,
"landing_successes": 30,
"landing_type": "ASDS",
"wikipedia":
"https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship",
"details":
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
"status": "active",
"id": "5e9e3032383ecb6bb234e7ca"
}
}
],
"id": "5eb87cd9ffd86e000604b32a"
}),
RocketDetails(
fairings: FairingsDetails(
reused: true,
recoveryAttempt: true,
recovered: true,
),
cores: [
Core(
block: 5,
reuseCount: 0,
rtlsAttempts: 0,
rtlsLandings: 0,
asdsAttempts: 0,
asdsLandings: 0,
lastUpdate:
'Engine failure at T+33 seconds resulted in loss of vehicle',
launches: [
LaunchDetails(
flightNumber: 1,
name: 'FalconSat',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87cd9ffd86e000604b32a',
),
],
serial: 'Merlin1A',
status: 'lost',
id: '5e9e289df35918033d3b2623',
hasGridfins: false,
hasLegs: false,
reused: false,
landingAttempt: false,
landingSuccess: false,
landpad: LandpadDetails(
name: 'OCISLY',
fullName: 'Of Course I Still Love You',
type: 'ASDS',
locality: 'Port Canaveral',
region: 'Florida',
latitude: 28.4104,
longitude: -80.6188,
landingAttempts: 36,
landingSuccesses: 30,
wikipediaUrl:
'https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship',
details:
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
status: 'active',
id: '5e9e3032383ecb6bb234e7ca',
),
),
],
payloads: [
Payload(
capsule: CapsuleDetails(
reuseCount: 1,
splashings: 1,
lastUpdate: 'descripction',
launches: [
LaunchDetails(
flightNumber: 10,
name: 'CRS-2',
date: DateTime.parse('2015-06-28T14:21:00.000Z'),
id: '5eb87ce1ffd86e000604b333',
)
],
serial: 'C104',
status: 'unknown',
type: 'Dragon 1.0',
id: '5e9e2c5bf359189ef23b2667',
),
name: 'FalconSAT-2',
reused: true,
customer: 'DARPA',
nationality: 'United States',
manufacturer: 'SSTL',
mass: 20,
orbit: 'LEO',
periapsis: 400,
apoapsis: 500,
inclination: 39,
period: 90.0,
id: '5eb0e4b5b6c3bb0006eeb1e1',
),
],
name: 'Falcon 1',
id: '5e9d0d95eda69955f709d1eb',
),
);
});
test('correctly checks whether rocket is heavy', () {
expect(
RocketDetails(cores: const [Core()]).isHeavy,
false,
);
expect(
RocketDetails(cores: const [Core(), Core(), Core()]).isHeavy,
true,
);
});
test('correctly checks whether rocket has fairings', () {
expect(
RocketDetails(fairings: FairingsDetails()).hasFairings,
true,
);
expect(
RocketDetails().hasFairings,
false,
);
});
test('correctly returns single core', () {
expect(
RocketDetails(
cores: const [Core(id: '1'), Core(id: '2'), Core(id: '3')])
.getSingleCore,
Core(id: '1'),
);
});
test('correctly checks whether core is a side one', () {
final cores = [Core(id: '1'), Core(id: '2'), Core(id: '3')];
expect(
RocketDetails(id: '', cores: cores).isSideCore(cores[0]),
false,
);
expect(
RocketDetails(id: '', cores: cores).isSideCore(cores[1]),
true,
);
expect(
RocketDetails(id: '', cores: cores).isSideCore(cores[2]),
true,
);
expect(
RocketDetails(id: '', cores: [cores[0]]).isSideCore(cores[0]),
false,
);
});
test('correctly checks for a null first stage', () {
final cores = [Core(id: '1'), Core(id: '2'), Core(id: '3')];
expect(
RocketDetails(cores: cores).isFirstStageNull,
false,
);
expect(
RocketDetails(cores: const [Core()]).isFirstStageNull,
true,
);
});
test('correctly checks for multiple payload', () {
expect(
RocketDetails(payloads: const [Payload()]).hasMultiplePayload,
false,
);
expect(
RocketDetails(payloads: const [Payload(), Payload()])
.hasMultiplePayload,
true,
);
});
test('correctly returns single payload', () {
expect(
RocketDetails(payloads: const [Payload(id: '1')]).getSinglePayload,
Payload(id: '1'),
);
});
test('correctly checks for dragon capsule', () {
expect(
RocketDetails(
payloads: const [Payload(id: '1', capsule: CapsuleDetails())])
.hasCapsule,
true,
);
expect(
RocketDetails(payloads: const [Payload(id: '1')]).hasCapsule,
false,
);
});
test('correctly returns short tentative time', () {
expect(
RocketDetails(
cores: const [Core(id: '1'), Core(id: '2'), Core(id: '3')])
.getCore('1'),
Core(id: '1'),
);
});
});
group('FairingsDetails', () {
test('is correctly generated from a JSON', () {
expect(
FairingsDetails.fromJson(const {
"reused": true,
"recovery_attempt": true,
"recovered": true,
"ships": [
{
"name": "GO Ms Tree",
"id": "5ea6ed2e080df4000697c908",
}
]
}),
FairingsDetails(
reused: true,
recoveryAttempt: true,
recovered: true,
),
);
});
});
group('FailureDetails', () {
test('is correctly generated from a JSON', () {
expect(
FailureDetails.fromJson(const {
"time": 139,
"altitude": 40,
"reason":
"helium tank overpressure lead to the second stage LOX tank explosion"
}),
FailureDetails(
time: 139,
altitude: 40,
reason:
"helium tank overpressure lead to the second stage LOX tank explosion",
),
);
});
test('correctly returns time', () {
expect(
FailureDetails(time: 59).getTime,
'T+59 s',
);
expect(
FailureDetails(time: 3599).getTime,
'T+59min 59s',
);
expect(
FailureDetails(time: 3600).getTime,
'T+1h 0min',
);
});
test('correctly returns reason', () {
expect(
FailureDetails(reason: 'test').getReason,
'Test',
);
});
test('correctly returns altitude', () {
expect(
FailureDetails().getAltitude(MockBuildContext()),
'spacex.other.unknown',
);
expect(
FailureDetails(altitude: 100).getAltitude(MockBuildContext()),
'100 km',
);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/launches_test.dart | import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:cherry/services/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'mock.dart';
class MockLaunchesService extends Mock implements LaunchesService {}
void main() {
group('LaunchesRepository', () {
MockLaunchesService service;
LaunchesRepository repository;
setUp(() {
service = MockLaunchesService();
repository = LaunchesRepository(service);
});
test('returns request when service returns 200', () async {
final response = MockResponse();
const json = {
'docs': [
{
"fairings": {
"reused": true,
"recovery_attempt": true,
"recovered": true,
"ships": [
{"name": "GO Ms Tree", "id": "5ea6ed2e080df4000697c908"}
]
},
"links": {
"patch": {
"small": "https://images2.imgbox.com/3c/0e/T8iJcSN3_o.png"
},
"reddit": {
"campaign": "http",
},
"flickr": {
"original": [
"https://farm8.staticflickr.com/7615/16670240949_8d43db0e36_o.jpg",
"https://farm9.staticflickr.com/8597/16856369125_e97cd30ef7_o.jpg",
"https://farm8.staticflickr.com/7586/16166732954_9338dc859c_o.jpg",
"https://farm8.staticflickr.com/7603/16855223522_462da54e84_o.jpg",
"https://farm8.staticflickr.com/7618/16234010894_e1210ec300_o.jpg",
"https://farm8.staticflickr.com/7617/16855338881_69542a2fa9_o.jpg"
]
},
"presskit": "http",
"webcast": "https://www.youtube.com/watch?v=0a_00nJ_Y88"
},
"static_fire_date_utc": "2006-03-17T00:00:00.000Z",
"tbd": false,
"net": false,
"window": 0,
"rocket": {
"name": "Falcon 1",
"id": "5e9d0d95eda69955f709d1eb",
},
"success": false,
"failures": [
{
"time": 139,
"altitude": 40,
"reason":
"helium tank overpressure lead to the second stage LOX tank explosion"
}
],
"details": "Engine failure at 33 seconds and loss of vehicle",
"payloads": [
{
"dragon": {
"capsule": {
"reuse_count": 1,
"water_landings": 1,
"last_update": "descripction",
"launches": [
{
"flight_number": 10,
"name": "CRS-2",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87ce1ffd86e000604b333"
}
],
"serial": "C104",
"status": "unknown",
"type": "Dragon 1.0",
"id": "5e9e2c5bf359189ef23b2667"
}
},
"name": "FalconSAT-2",
"reused": true,
"customers": ["DARPA"],
"nationalities": ["United States"],
"manufacturers": ["SSTL"],
"mass_kg": 20,
"orbit": "LEO",
"periapsis_km": 400,
"apoapsis_km": 500,
"inclination_deg": 39,
"period_min": 90.0,
"id": "5eb0e4b5b6c3bb0006eeb1e1"
}
],
"launchpad": {
'images': {
'large': ['image.com']
},
"name": "Kwajalein Atoll",
"full_name": "Kwajalein Atoll Omelek Island",
"locality": "Omelek Island",
"region": "Marshall Islands",
"latitude": 9.0477206,
"longitude": 167.7431292,
"launch_attempts": 5,
"launch_successes": 2,
"details":
"SpaceX's primary Falcon 9 pad, where all east coast Falcon 9s launched prior to the AMOS-6 anomaly. Previously used alongside SLC-41 to launch Titan rockets for the US Air Force, the pad was heavily damaged by the AMOS-6 anomaly in September 2016. It returned to flight with CRS-13 on December 15, 2017, boasting an upgraded throwback-style Transporter-Erector modeled after that at LC-39A.",
"id": "5e9e4502f5090995de566f86"
},
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2006-03-24T22:30:00.000Z",
"date_precision": "hour",
"upcoming": false,
"cores": [
{
"core": {
"block": 5,
"reuse_count": 0,
"rtls_attempts": 0,
"rtls_landings": 0,
"asds_attempts": 0,
"asds_landings": 0,
"last_update":
"Engine failure at T+33 seconds resulted in loss of vehicle",
"launches": [
{
"flight_number": 1,
"name": "FalconSat",
"date_utc": "2015-06-28T14:21:00.000Z",
"id": "5eb87cd9ffd86e000604b32a"
}
],
"serial": "Merlin1A",
"status": "lost",
"id": "5e9e289df35918033d3b2623"
},
"gridfins": false,
"legs": false,
"reused": false,
"landing_attempt": false,
"landing_success": false,
"landpad": {
'images': {
'large': ['image.com']
},
"name": "OCISLY",
"full_name": "Of Course I Still Love You",
"type": "ASDS",
"locality": "Port Canaveral",
"region": "Florida",
"latitude": 28.4104,
"longitude": -80.6188,
"landing_attempts": 36,
"landing_successes": 30,
"landing_type": "ASDS",
"wikipedia":
"https://en.wikipedia.org/wiki/Autonomous_spaceport_drone_ship",
"details":
"The second ASDS barge, Of Course I Still Love You (OCISLY), had been under construction in a Louisiana shipyard since early 2015 using a different hull—Marmac 304—in order to service launches on the east coast. It was built as a replacement for the first Just Read the Instructions and entered operational service for Falcon 9 Flight 19 in late June 2015. As of June 2015, its home port was Jacksonville, Florida, but after December 2015, it was transferred 160 miles (260 km) further south, at Port Canaveral. While the dimensions of the ship are nearly identical to the first ASDS, several enhancements were made including a steel blast wall erected between the aft containers and the landing deck. The ship was in place for a first-stage landing test on the CRS-7 mission, which failed on launch on 28 June 2015. On 8 April 2016 the first stage, which launched the Dragon CRS-8 spacecraft, successfully landed for the first time ever on OCISLY, which is also the first ever drone ship landing. In February 2018, the Falcon Heavy Test Flight's central core exploded upon impact next to OCISLY that damaged two of the four thrusters on the drone ship. Two thrusters were removed from the Marmac 303 barge in order to repair OCISLY.",
"status": "active",
"id": "5e9e3032383ecb6bb234e7ca"
}
}
],
"id": "5eb87cd9ffd86e000604b32a"
}
]
};
when(response.data).thenReturn(json);
when(service.getLaunches()).thenAnswer((_) => Future.value(response));
final output = await repository.fetchData();
expect(output, [
[],
[Launch.fromJson(json['docs'].single)]
]);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/achievements_test.dart | import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:cherry/services/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'mock.dart';
class MockAchievementsService extends Mock implements AchievementsService {}
void main() {
group('AchievementsRepository', () {
MockAchievementsService service;
AchievementsRepository repository;
setUp(() {
service = MockAchievementsService();
repository = AchievementsRepository(service);
});
test('returns request when client returns 200', () async {
final response = MockResponse();
const json = [
{
"links": {
"article":
"http://www.spacex.com/news/2013/02/11/flight-4-launch-update-0"
},
"title": "Falcon reaches Earth orbit",
"event_date_utc": "2008-09-28T23:15:00Z",
"event_date_unix": 1222643700,
"details":
"Falcon 1 becomes the first privately developed liquid-fuel rocket to reach Earth orbit.",
"id": "5f6fb2cfdcfdf403df37971e"
}
];
when(
service.getAchievements(),
).thenAnswer((_) => Future.value(response));
when(response.data).thenReturn(json);
final output = await repository.fetchData();
expect(output, [Achievement.fromJson(json.first)]);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/changelog_test.dart | import 'package:cherry/repositories/index.dart';
import 'package:cherry/services/changelog.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'mock.dart';
class MockChangelogService extends Mock implements ChangelogService {}
void main() {
group('ChangelogRepository', () {
ChangelogService service;
ChangelogRepository repository;
setUp(() {
service = MockChangelogService();
repository = ChangelogRepository(service);
});
test('returns request when client returns 200', () async {
final response = MockResponse();
const json = 'Just a normal JSON here';
when(
service.getChangelog(),
).thenAnswer((_) => Future.value(response));
when(response.data).thenReturn(json);
final output = await repository.fetchData();
expect(output, json);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/company_test.dart | import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:cherry/services/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'mock.dart';
class MockCompanyService extends Mock implements CompanyService {}
void main() {
group('CompanyRepository', () {
MockCompanyService service;
CompanyRepository repository;
setUp(() {
service = MockCompanyService();
repository = CompanyRepository(service);
});
test('returns request when service returns 200', () async {
final response = MockResponse();
const json = {
'headquarters': {
'address': 'Rocket Road',
'city': 'Hawthorne',
'state': 'California'
},
'links': {
'website': 'https://www.spacex.com/',
'flickr': 'https://www.flickr.com/photos/spacex/',
'twitter': 'https://twitter.com/SpaceX',
'elon_twitter': 'https://twitter.com/elonmusk'
},
'name': 'SpaceX',
'founder': 'Elon Musk',
'founded': 2002,
'employees': 8000,
'vehicles': 3,
'launch_sites': 3,
'test_sites': 1,
'ceo': 'Elon Musk',
'cto': 'Elon Musk',
'coo': 'Gwynne Shotwell',
'cto_propulsion': 'Tom Mueller',
'valuation': 52000000000,
'summary':
'SpaceX designs, manufactures and launches advanced rockets and spacecraft. The company was founded in 2002 to revolutionize space technology, with the ultimate goal of enabling people to live on other planets.',
'id': '5eb75edc42fea42237d7f3ed'
};
when(response.data).thenReturn(json);
when(
service.getCompanyInformation(),
).thenAnswer((_) => Future.value(response));
final output = await repository.fetchData();
expect(output, CompanyInfo.fromJson(json));
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/mock.dart | import 'package:dio/dio.dart';
import 'package:mockito/mockito.dart';
class MockClient extends Mock implements Dio {}
class MockResponse extends Mock implements Response {}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/repositories/vehicles_test.dart | import 'package:cherry/models/index.dart';
import 'package:cherry/repositories/index.dart';
import 'package:cherry/services/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'mock.dart';
class MockVehiclesService extends Mock implements VehiclesService {}
void main() {
group('VehiclesRepository', () {
MockVehiclesService service;
VehiclesRepository repository;
setUp(() {
service = MockVehiclesService();
repository = VehiclesRepository(service);
});
test('returns request when service returns 200', () async {
final roadsterResponse = MockResponse();
const roadsterJson = {
"flickr_images": [
"https://farm5.staticflickr.com/4615/40143096241_11128929df_b.jpg",
"https://farm5.staticflickr.com/4702/40110298232_91b32d0cc0_b.jpg",
"https://farm5.staticflickr.com/4676/40110297852_5e794b3258_b.jpg",
"https://farm5.staticflickr.com/4745/40110304192_6e3e9a7a1b_b.jpg"
],
"name": "Elon Musk's Tesla Roadster",
"launch_date_utc": "2018-02-06T20:45:00.000Z",
"launch_date_unix": 1517949900,
"launch_mass_kg": 1350,
"launch_mass_lbs": 2976,
"norad_id": 43205,
"epoch_jd": 2459099.747048611,
"orbit_type": "heliocentric",
"apoapsis_au": 1.663953958687046,
"periapsis_au": 0.9858147198091061,
"semi_major_axis_au": 251.4894388260824,
"eccentricity": 0.2559239394673542,
"inclination": 1.077447168391629,
"longitude": 317.0814558060362,
"periapsis_arg": 177.5319554749398,
"period_days": 557.0130583804103,
"speed_kph": 81565.80012,
"speed_mph": 50682.62278636452,
"earth_distance_km": 91218798.05943623,
"earth_distance_mi": 56680715.76898995,
"mars_distance_km": 22540919.9995336,
"mars_distance_mi": 14006274.001030194,
"wikipedia":
"https://en.wikipedia.org/wiki/Elon_Musk%27s_Tesla_Roadster",
"video": "https://youtu.be/wbSwFU6tY1c",
"details":
"Elon Musk's Tesla Roadster is an electric sports car that served as the dummy payload for the February 2018 Falcon Heavy test flight and is now an artificial satellite of the Sun. Starman, a mannequin dressed in a spacesuit, occupies the driver's seat. The car and rocket are products of Tesla and SpaceX. This 2008-model Roadster was previously used by Musk for commuting, and is the only consumer car sent into space.",
"id": "5eb75f0842fea42237d7f3f4"
};
final dragonResponse = MockResponse();
const dragonJson = {
'docs': [
{
'launch_payload_mass': {'kg': 6000},
'return_payload_mass': {'kg': 3000},
'height_w_trunk': {'meters': 7.2},
'diameter': {'meters': 3.7},
'first_flight': '2010-12-08',
'flickr_images': [
'https://i.imgur.com/9fWdwNv.jpg',
'https://live.staticflickr.com/8578/16655995541_7817565ea9_k.jpg',
'https://farm3.staticflickr.com/2815/32761844973_4b55b27d3c_b.jpg',
'https://farm9.staticflickr.com/8618/16649075267_d18cbb4342_b.jpg'
],
'name': 'Dragon 1',
'type': 'capsule',
'active': true,
'crew_capacity': 0,
'dry_mass_kg': 4200,
'thrusters': [
{
'type': 'Draco',
'amount': 18,
'fuel_1': 'nitrogen tetroxide',
'fuel_2': 'monomethylhydrazine',
'isp': 300,
'thrust': {'kN': 0.4}
}
],
'wikipedia': 'https://en.wikipedia.org/wiki/SpaceX_Dragon',
'description':
'Dragon is a reusable spacecraft developed by SpaceX, an American private space transportation company based in Hawthorne, California. Dragon is launched into space by the SpaceX Falcon 9 two-stage-to-orbit launch vehicle. The Dragon spacecraft was originally designed for human travel, but so far has only been used to deliver cargo to the International Space Station (ISS).',
'id': '5e9d058759b1ff74a7ad5f8f'
}
]
};
final rocketResponse = MockResponse();
const rocketJson = {
'docs': [
{
'height': {'meters': 22.25},
'diameter': {'meters': 1.68},
'mass': {'kg': 30146},
'first_stage': {
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 44.3
},
'second_stage': {
'thrust': {'kN': 31},
'payloads': {
'composite_fairing': {
'height': {'meters': 3.5},
'diameter': {'meters': 1.5}
}
},
'reusable': false,
'engines': 1,
'fuel_amount_tons': 3.38
},
'engines': {
'isp': {'sea_level': 267, 'vacuum': 304},
'thrust_sea_level': {'kN': 420},
'thrust_vacuum': {'kN': 480},
'type': 'merlin',
'version': '1C',
'propellant_1': 'liquid oxygen',
'propellant_2': 'RP-1 kerosene',
'thrust_to_weight': 96
},
'payload_weights': [
{'id': 'leo', 'name': 'Low Earth Orbit', 'kg': 450}
],
'flickr_images': [
'https://imgur.com/DaCfMsj.jpg',
'https://imgur.com/azYafd8.jpg'
],
'name': 'Falcon 1',
'type': 'rocket',
'active': false,
'stages': 2,
'boosters': 0,
'cost_per_launch': 6700000,
'success_rate_pct': 40,
'first_flight': '2006-03-24',
'wikipedia': 'https://en.wikipedia.org/wiki/Falcon_1',
'description':
'The Falcon 1 was an expendable launch system privately developed and manufactured by SpaceX during 2006-2009. On 28 September 2008, Falcon 1 became the first privately-developed liquid-fuel launch vehicle to go into orbit around the Earth.',
'id': '5e9d0d95eda69955f709d1eb'
}
]
};
final shipResponse = MockResponse();
const shipJson = {
'docs': [
{
'model': 'Boat',
'type': 'High Speed Craft',
'roles': ['Fairing Recovery'],
'mass_kg': 449964,
'year_built': 2015,
'home_port': 'Port Canaveral',
'status': 'status',
'speed_kn': 200,
'link':
'https://www.marinetraffic.com/en/ais/details/ships/shipid:3439091/mmsi:368099550/imo:9744465/vessel:GO_MS_TREE',
'image': 'https://i.imgur.com/MtEgYbY.jpg',
'launches': [
{
'flight_number': 50,
'name': 'KoreaSat 5A',
'id': '5eb87d0dffd86e000604b35b'
}
],
'name': 'GO Ms Tree',
'active': true,
'id': '5ea6ed2e080df4000697c908'
}
]
};
when(
service.getRoadster(),
).thenAnswer((_) => Future.value(roadsterResponse));
when(roadsterResponse.data).thenReturn(roadsterJson);
when(
service.getDragons(),
).thenAnswer((_) => Future.value(dragonResponse));
when(dragonResponse.data).thenReturn(dragonJson);
when(
service.getRockets(),
).thenAnswer((_) => Future.value(rocketResponse));
when(rocketResponse.data).thenReturn(rocketJson);
when(
service.getShips(),
).thenAnswer((_) => Future.value(shipResponse));
when(shipResponse.data).thenReturn(shipJson);
final output = await repository.fetchData();
expect(output, [
RoadsterVehicle.fromJson(roadsterJson),
DragonVehicle.fromJson(dragonJson['docs'].single),
RocketVehicle.fromJson(rocketJson['docs'].single),
ShipVehicle.fromJson(shipJson['docs'].single),
]);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/utils/bloc_observer_test.dart | import 'package:bloc/bloc.dart';
import 'package:cherry/utils/index.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
class MockBloc extends Mock implements Bloc<Object, int> {}
// ignore: must_be_immutable, avoid_implementing_value_types
class MockTransition extends Mock implements Transition<Object, int> {}
void main() {
group('BlocObserver', () {
group('onCreate', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onCreate(MockBloc());
});
});
group('onEvent', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onEvent(MockBloc(), Object());
});
});
group('onChange', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onChange(MockBloc(), MockTransition());
});
});
group('onTransition', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onTransition(MockBloc(), MockTransition());
});
});
group('onError', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onError(MockBloc(), Object(), StackTrace.current);
});
});
group('onClose', () {
test('does nothing by default', () {
// ignore: invalid_use_of_protected_member
CherryBlocObserver().onClose(MockBloc());
});
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/utils/launch_utils_test.dart | import 'package:cherry/models/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LaunchUtils', () {
final _launches = [
[
Launch(
id: '0',
upcoming: true,
launchDate: DateTime.now().add(Duration(days: 1)),
),
Launch(
id: '1',
upcoming: true,
launchDate: DateTime.now().add(Duration(days: 2)),
),
],
[
Launch(
id: '2',
upcoming: false,
launchDate: DateTime.now().subtract(Duration(days: 1)),
),
Launch(
id: '3',
upcoming: false,
launchDate: DateTime.now().subtract(Duration(days: 2)),
),
]
];
test('returns upcoming launch correctly', () {
expect(LaunchUtils.getUpcomingLaunch(_launches).id, '0');
});
test('returns latest launch correctly', () {
expect(LaunchUtils.getLatestLaunch(_launches).id, '2');
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/launches_test.dart | import 'package:cherry/services/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import './mock.dart';
void main() {
group('LaunchesService', () {
MockClient client;
LaunchesService service;
setUp(() {
client = MockClient();
service = LaunchesService(client);
});
test('returns launches when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.post(
Url.launches,
data: ApiQuery.launch,
),
).thenAnswer((_) => Future.value(response));
final output = await service.getLaunches();
expect(output.data, json);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/achievements_test.dart | import 'package:cherry/services/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import './mock.dart';
void main() {
group('AchievementsService', () {
MockClient client;
AchievementsService service;
setUp(() {
client = MockClient();
service = AchievementsService(client);
});
test('returns Achievements when client returns 200', () async {
const json = ['Just a normal JSON here'];
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.get(Url.companyAchievements),
).thenAnswer((_) => Future.value(response));
final output = await service.getAchievements();
expect(output.data.cast<String>(), json);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/changelog_test.dart | import 'package:cherry/services/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import './mock.dart';
void main() {
group('ChangelogService', () {
MockClient client;
ChangelogService service;
setUp(() {
client = MockClient();
service = ChangelogService(client);
});
test('returns changelog when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.get(Url.changelog),
).thenAnswer((_) => Future.value(response));
final output = await service.getChangelog();
expect(output.data, json);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/company_test.dart | import 'package:cherry/services/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import './mock.dart';
void main() {
group('CompanyService', () {
MockClient client;
CompanyService service;
setUp(() {
client = MockClient();
service = CompanyService(client);
});
test('returns Achievements when client returns 200', () async {
const json = ['Just a normal JSON here'];
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.get(Url.companyAchievements),
).thenAnswer((_) => Future.value(response));
});
test('returns CompanyInfo when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.get(Url.companyInformation),
).thenAnswer((_) => Future.value(response));
final output = await service.getCompanyInformation();
expect(output.data, json);
});
});
}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/mock.dart | import 'package:dio/dio.dart';
import 'package:mockito/mockito.dart';
class MockClient extends Mock implements Dio {}
class MockResponse extends Mock implements Response {}
| 0 |
mirrored_repositories/spacex-go/test | mirrored_repositories/spacex-go/test/services/vehicles_test.dart | import 'package:cherry/services/index.dart';
import 'package:cherry/utils/index.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import './mock.dart';
void main() {
group('VehiclesService', () {
MockClient client;
VehiclesService service;
setUp(() {
client = MockClient();
service = VehiclesService(client);
});
test('returns dragon request when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.post(
Url.dragons,
data: ApiQuery.dragonVehicle,
),
).thenAnswer((_) => Future.value(response));
final output = await service.getDragons();
expect(output.data, json);
});
test('returns roadster request when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.post(
Url.roadster,
data: ApiQuery.roadsterVehicle,
),
).thenAnswer((_) => Future.value(response));
final output = await service.getRoadster();
expect(output.data, json);
});
test('returns rockets request when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.post(
Url.rockets,
data: ApiQuery.rocketVehicle,
),
).thenAnswer((_) => Future.value(response));
final output = await service.getRockets();
expect(output.data, json);
});
test('returns ships request when client returns 200', () async {
const json = 'Just a normal JSON here';
final response = MockResponse();
when(response.statusCode).thenReturn(200);
when(response.data).thenReturn(json);
when(
client.post(
Url.ships,
data: ApiQuery.shipVehicle,
),
).thenAnswer((_) => Future.value(response));
final output = await service.getShips();
expect(output.data, json);
});
});
}
| 0 |
mirrored_repositories/All-Hadith | mirrored_repositories/All-Hadith/lib/main.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:statefull/router/EnterBook.dart';
import 'cilpper/HomeClipper.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<List> book;
@override
Future<List> getBooks() async {
http.Response res =
await http.get(Uri.parse("https://alquranbd.com/api/hadith"));
return jsonDecode(res.body);
}
@override
void initState() {
super.initState();
this.book = getBooks();
}
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text('All Hadith')),
),
body: Center(
child: Container(
child: FutureBuilder(
future: this.book,
builder: (context, AsyncSnapshot<List> mySnapshot) {
if (mySnapshot.hasData) {
List? books = mySnapshot.data;
return ListView.builder(
itemCount: books!.length,
itemBuilder: (BuildContext context, i) => Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
color: Colors.cyanAccent,
child: Row(
children: [
Expanded(
flex: 1,
child: Stack(
children: [
Opacity(
opacity: 0.5,
child: ClipPath(
child: Container(
color: Colors.deepOrangeAccent,
height: 250,
width: double.infinity,
),
clipper: MyClipper(),
),
),
ClipPath(
child: RaisedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => EnterBook(
book_key: books[i]
["book_key"]
.toString())));
},
child: Container(
height: 230,
width: double.infinity,
child: ListTile(
leading: CircleAvatar(
child: Text(books[i]["id"]),
),
title: Text(books[i]["nameBengali"]),
subtitle:
Text(books[i]["nameEnglish"]),
trailing: Text("Number Of Hadith: " +
books[i]["hadith_number"]),
),
),
clipBehavior: Clip.antiAliasWithSaveLayer,
color: Colors.deepOrangeAccent,
),
clipper: MyClipper(),
),
],
),
),
],
),
),
),
);
} else if (mySnapshot.hasError)
return Text("Error Loading Data...");
return CircularProgressIndicator();
},
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/All-Hadith/lib | mirrored_repositories/All-Hadith/lib/router/EnterBook.dart | // ignore_for_file: file_names
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:statefull/main.dart';
import 'package:statefull/router/Hadith.dart';
class EnterBook extends StatefulWidget {
const EnterBook({
Key? key,
required String? this.book_key,
}) : super(key: key);
final String? book_key;
@override
_EnterBookState createState() => _EnterBookState();
}
class _EnterBookState extends State<EnterBook> {
late Future<List> books;
@override
Future<List> getBooks(String? book_key) async {
http.Response res =
await http.get(Uri.parse("https://alquranbd.com/api/hadith/$book_key"));
if (res.statusCode == 200) {
//print(res.body);
var x = jsonDecode(res.body);
// print(x[0]);
return x;
} else {
// print("error");
throw Exception("error");
}
}
@override
void initState() {
super.initState();
this.books = getBooks(widget.book_key!);
//print();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_rounded),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => MyApp()));
},
),
title: Center(child: Text("All Hadith")),
),
body: Center(
child: FutureBuilder(
future: this.books,
builder: (context, AsyncSnapshot<List> sn) {
if (sn.hasData) {
List? finalBook = sn.data;
int ln = finalBook!.length;
String s = "01234567890/১২০৩৪৫৬৭৮৯";
for (int i = 0; i < ln; i++) {
String ss = "";
for (int j = 0;
j < finalBook[i]["nameBengali"].length;
j++) {
bool ok = false;
for (int k = 0; k < s.length; k++) {
if (finalBook[i]["nameBengali"][j] == s[k]) {
ok = true;
break;
}
}
if (ok) continue;
ss = ss.toString() + finalBook[i]["nameBengali"][j];
}
finalBook[i]["nameBengali"] = ss;
String bs = "";
for (int j = 0;
j < finalBook[i]["nameEnglish"].length;
j++) {
bool ok = false;
for (int k = 0; k < s.length; k++) {
if (finalBook[i]["nameEnglish"][j] == s[k]) {
ok = true;
break;
}
}
if (ok) continue;
bs = bs.toString() + finalBook[i]["nameEnglish"][j];
}
finalBook[i]["nameEnglish"] = bs;
}
return ListView.builder(
itemCount: ln,
itemBuilder: (context, i) => Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => hadith(
chapNo: finalBook[i]["chSerial"].toString(),
book_key: widget.book_key)));
},
color: Colors.cyan.shade100,
hoverColor: Colors.cyanAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
child: ListTile(
leading: CircleAvatar(
child: Text(finalBook[i]["chSerial"]),
),
title: Text(finalBook[i]["nameBengali"]),
subtitle: Text(finalBook[i]["nameEnglish"]),
trailing: Text("Number Of Hadith: " +
finalBook[i]["hadith_number"] +
"\n" +
finalBook[i]["range_start"] +
" to " +
finalBook[i]["range_end"]),
),
),
),
);
} else if (sn.hasError) return Text("Error Loading Data...");
return CircularProgressIndicator();
}),
),
),
);
}
}
| 0 |
mirrored_repositories/All-Hadith/lib | mirrored_repositories/All-Hadith/lib/router/Hadith.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:statefull/main.dart';
import 'package:statefull/router/EnterBook.dart';
import 'package:statefull/router/Hadith.dart';
class hadith extends StatefulWidget {
const hadith({
Key? key,
required String? this.chapNo,
required String? this.book_key,
}) : super(key: key);
final String? chapNo;
final String? book_key;
@override
_hadithState createState() => _hadithState();
}
class _hadithState extends State<hadith> {
late Future<List> hadith;
Future<List> getBook(String? chaptNo, String? books_key) async {
http.Response res = await http
.get(Uri.parse("https://alquranbd.com/api/hadith/$books_key/$chaptNo"));
if (res.statusCode == 200) {
//print(res.body);
var x = jsonDecode(res.body);
// print(x[0]);
return x;
} else {
// print("error");
throw Exception("error");
}
}
@override
void initState() {
super.initState();
this.hadith = getBook(widget.chapNo, widget.book_key);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_rounded),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
EnterBook(book_key: widget.book_key.toString())));
},
),
title: Center(child: Text("All Hadith")),
),
body: Center(
child: FutureBuilder(
future: this.hadith,
builder: (context, AsyncSnapshot<List> sn) {
if (sn.hasData) {
List? finalBook = sn.data;
int ln = finalBook!.length;
for (int i = 0; i < ln; i++) {
String? s = "";
String ss =
"<>1234567890-=!@#%^&*_+`~qwertyuiop[]}{POIUYTREWQasdfghjkl;\|:LKJH'GFDSA\zxcvbnm,.%.,mnbvcxz\"";
for (int j = 0;
j < finalBook[i]["hadithBengali"].length;
j++) {
bool ok = false;
for (int k = 0; k < ss.length; k++) {
if (ss[k] == finalBook[i]["hadithBengali"][j]) {
ok = true;
// print("find");
break;
}
}
if (ok) continue;
s = s.toString() + finalBook[i]["hadithBengali"][j];
// int x =(char)finalBook[i]["hadithBengali"][j] - '0';
// print(s);
}
finalBook[i]["hadithBengali"] = s;
}
return ListView.builder(
itemCount: ln,
itemBuilder: (context, i) => Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {},
color: Colors.cyan.shade100,
hoverColor: Colors.cyanAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
child: Column(
children: [
Center(
child: Text(
"হাদীস নং : " + finalBook[i]["hadithNo"],
style: TextStyle(
fontSize: 20,
),
),
),
Text(
finalBook[i]["hadithArabic"],
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w900,
height: 2,
),
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(
finalBook[i]["hadithBengali"],
style: TextStyle(
fontSize: 20,
),
),
),
],
)),
),
);
} else if (sn.hasError) return Text("Error Loading Data...");
return CircularProgressIndicator();
}),
),
),
);
}
}
| 0 |
mirrored_repositories/All-Hadith/lib | mirrored_repositories/All-Hadith/lib/cilpper/HomeClipper.dart | import 'package:flutter/material.dart';
class MyClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
// TODO: implement getClip
// debugPrint(size.width.toString());
// debugPrint(size.height.toString());
var path = new Path();
path.lineTo(0.0, size.height - 50);
var start1 = Offset(size.width / 5, size.height - 50);
var end1 = Offset(size.width / 2.5, size.height - 100.0);
path.quadraticBezierTo(start1.dx, start1.dy, end1.dx, end1.dy);
var end2 = Offset(size.width, size.height - 60);
var start2 = Offset(size.width - (size.width / 3.24), size.height - 155.0);
path.quadraticBezierTo(start2.dx, start2.dy, end2.dx, end2.dy);
path.lineTo(size.width, 0);
// path.close();
//print(path);
return path;
//throw UnimplementedError();
//print("dvkjd");
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
| 0 |
mirrored_repositories/All-Hadith | mirrored_repositories/All-Hadith/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:statefull/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/TimeLuxe | mirrored_repositories/TimeLuxe/lib/main.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:reusable_components/reusable_components.dart';
import '/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import '/core/global/app_theme.dart';
import '/features/splash/presnetation/view/splash_view.dart';
import 'core/utils/helper.dart';
import 'core/network/local/cache_helper.dart';
import 'core/utils/firebase_options.dart';
import 'core/utils/my_bloc_observer.dart';
import 'core/utils/service_locator.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
Bloc.observer = MyBlocObserver();
ServiceLocator().setupServiceLocators();
await CacheHelper.initSharedPref();
setSystemUIOverlayStyle();
runApp(const TimeLuxeApp());
}
class TimeLuxeApp extends StatelessWidget {
const TimeLuxeApp({super.key});
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return BlocProvider(
create: (context) =>
serviceLocator.get<TimeLuxeCubit>()..getUserData(Helper.uId),
child: ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) => GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.appTheme(),
home: const SplashView(),
),
),
);
}
}
void setSystemUIOverlayStyle() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
SystemChrome.setSystemUIOverlayStyle(
CustomHelper.setTheSystemUIOverlayStyle(),
);
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe | mirrored_repositories/TimeLuxe/lib/TimeLuxe/data/time_luxe_repo_impl.dart | import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import '../../core/models/user_model.dart';
import '../../core/utils/helper.dart';
import '../domain/time_luxe_repo.dart';
class TimeLuxeRepoImpl extends TimeLuxeRepo {
@override
Future<DocumentSnapshot<Map<String, dynamic>>> getUserData(
String? uId,
) async {
return await FirebaseFirestore.instance.collection('users').doc(uId).get();
}
@override
Future<void> updateUser({required UserModel userModel}) async {
return await FirebaseFirestore.instance
.collection('users')
.doc(Helper.model!.uId)
.update(userModel.toJson());
}
@override
Future<XFile?> getProfileImage({required ImageSource source}) async {
return await ImagePicker().pickImage(source: source);
}
@override
Future<TaskSnapshot> uploadProfileImage({
File? profileImage,
}) async {
return await firebase_storage.FirebaseStorage.instance
.ref()
.child('users/${Uri.file(profileImage!.path).pathSegments.last}')
.putFile(profileImage);
}
@override
Future<void> signOut() async {
await FirebaseAuth.instance.signOut();
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation | mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/view/time_luxe_app_view.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/TimeLuxe/presentation/widgets/time_luxe_app_view_body.dart';
import '../../../core/global/app_colors.dart';
import '../widgets/bottom_nav_bar.dart';
class TimeLuxeAppView extends StatelessWidget {
const TimeLuxeAppView({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TimeLuxeCubit, TimeLuxeStates>(
builder: (context, state) {
TimeLuxeCubit cubit = TimeLuxeCubit.getObject(context);
return Scaffold(
bottomNavigationBar: BottomNavBar(cubit: cubit),
backgroundColor: AppColors.backGroundColor,
body: TimeLuxeAppViewBody(cubit: cubit, state: state),
);
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/view | mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/domain/time_luxe_repo.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/core/global/app_constants.dart';
import 'package:time_luxe/core/utils/helper.dart';
import 'package:time_luxe/core/models/user_model.dart';
import 'package:time_luxe/features/welcome/presentation/views/welcome_view.dart';
import '../../../../core/models/watch_model.dart';
import '../../../../core/network/local/cache_helper.dart';
import '../../../../features/bag/presentation/widgets/bag_view_body.dart';
import '../../../../features/home/presentation/widgets/home_body.dart';
import '../../../../features/profile/presentation/widgets/profile_view_body.dart';
import '../../../../features/search/presentation/widgets/search_view_body.dart';
class TimeLuxeCubit extends Cubit<TimeLuxeStates> {
TimeLuxeCubit(this.timeLuxeRepo) : super(TimeLuxeInitialState());
static TimeLuxeCubit getObject(context) => BlocProvider.of(context);
TimeLuxeRepo timeLuxeRepo;
int ordersCounter = 1;
int currentIndex = 0;
bool passVisibility = true;
bool confirmPassVisibility = true;
void increment() {
ordersCounter++;
emit(IncrementSuccessState());
}
void decrement() {
if (ordersCounter > 1) {
ordersCounter--;
emit(DecrementSuccessState());
}
}
List<Widget> body = const <Widget>[
HomeBody(),
SearchViewBody(),
BagViewBody(),
ProfileViewBody(),
];
List<BottomNavigationBarItem> bottomNavItems =
const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Home',
icon: Icon(
Icons.home,
),
),
BottomNavigationBarItem(
label: 'Search',
icon: Icon(Icons.search),
),
BottomNavigationBarItem(
label: 'Bag',
icon: Icon(Icons.shopping_bag),
),
BottomNavigationBarItem(
label: 'Profile',
icon: Icon(Icons.person),
),
];
void changeBottomNavIndex(int index) {
currentIndex = index;
emit(ChangeBottomNavState());
}
void changeBottomNavToHome() {
currentIndex = 0;
emit(ChangeBottomNavToHome());
}
void changeBottomNavToBag() {
currentIndex = 2;
emit(ChangeBottomNavToHome());
}
void getUserData(String? uId) {
emit(GetUserLoadingState());
// Getting the user's id
uId = CacheHelper.getStringData(key: 'uId');
timeLuxeRepo.getUserData(uId).then((value) {
Helper.model = UserModel.fromJson(value.data()!);
emit(GetUserSuccessState());
debugPrint("USER HAS BEEN GOT");
}).catchError((error) {
GetUserErrorState(error.toString());
});
}
List<WatchModel> favorites = <WatchModel>[];
void addToFav(WatchModel favItem) {
favorites.add(favItem);
emit(AddToFavoriteSuccessState());
}
void removeFromFav(WatchModel favItem) {
favorites.remove(favItem);
emit(RemoveFromFavoriteSuccessState());
}
void addToBag(WatchModel bagProduct) {
AppConstants.bagItems.add(bagProduct);
emit(AddToBagSuccessState());
}
void removeBagProduct(WatchModel bagProduct) {
AppConstants.bagItems.remove(bagProduct);
emit(RemoveFromBagSuccessState());
}
double countAllBagPrices() {
double sum = 0;
for (int i = 0; i < AppConstants.bagItems.length; i++) {
sum += AppConstants.bagItems[i].price!;
}
return sum;
}
File? profileImage;
ImagePicker picker = ImagePicker();
Future<void> getProfileImage({required ImageSource source}) async {
await timeLuxeRepo.getProfileImage(source: source).then((value) {
if (value != null) {
profileImage = File(value.path);
emit(ProfileImagePickedSuccessState());
} else {
debugPrint("No image selected");
emit(ProfileImagePickedErrorState());
}
});
}
void uploadProfileImage({
required String name,
required String email,
required BuildContext context,
}) {
emit(UploadingProfileImageLoadingState());
timeLuxeRepo.uploadProfileImage(profileImage: profileImage).then((value) {
value.ref.getDownloadURL().then((value) {
emit(UploadProfileImageSuccessState());
updateUser(
name: name,
email: email,
image: value,
);
CustomHelper.buildSnackBar(
context: context,
message: "Profile Image Updated Successfully",
state: SnackBarStates.success,
title: "Success",
);
}).catchError((error) {
emit(UploadProfileImageErrorState());
});
}).catchError((error) {
emit(UploadProfileImageErrorState());
});
}
void updateUser({
required String name,
String? email,
String? image,
}) {
emit(UserUpdateLoadingState());
UserModel userModel = UserModel(
name: name,
image: image ?? Helper.model!.image,
email: email ?? Helper.model!.email,
uId: Helper.model!.uId,
);
timeLuxeRepo.updateUser(userModel: userModel).then((value) {
getUserData(Helper.uId);
}).catchError((error) {
emit(UserUpdateErrorState());
});
}
void signOut() {
timeLuxeRepo.signOut().then((value) {
CacheHelper.removeData(key: 'uId');
CustomNavigator.navigateAndFinish(screen: () => const WelcomeView());
emit(SignOutSuccessState());
}).catchError((error) {
debugPrint(error.toString());
emit(SignOutErrorState(error.toString()));
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/view | mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/view/manager/time_luxe_states.dart | abstract class TimeLuxeStates {}
class TimeLuxeInitialState extends TimeLuxeStates {}
class IncrementSuccessState extends TimeLuxeStates {}
class DecrementSuccessState extends TimeLuxeStates {}
class ChangeBottomNavState extends TimeLuxeStates {}
class ChangeBottomNavToHome extends TimeLuxeStates {}
class GetUserLoadingState extends TimeLuxeStates {}
class GetUserSuccessState extends TimeLuxeStates {}
class GetUserErrorState extends TimeLuxeStates {
final String error;
GetUserErrorState(this.error);
}
class UserUpdateLoadingState extends TimeLuxeStates {}
class UserUpdateErrorState extends TimeLuxeStates {}
class ProfileImagePickedSuccessState extends TimeLuxeStates {}
class ProfileImagePickedErrorState extends TimeLuxeStates {}
class UploadingProfileImageLoadingState extends TimeLuxeStates {}
class UploadProfileImageSuccessState extends TimeLuxeStates {}
class UploadProfileImageErrorState extends TimeLuxeStates {}
class AddToFavoriteSuccessState extends TimeLuxeStates {}
class RemoveFromFavoriteSuccessState extends TimeLuxeStates {}
class AddToBagSuccessState extends TimeLuxeStates {}
class RemoveFromBagSuccessState extends TimeLuxeStates {}
class SignOutSuccessState extends TimeLuxeStates {}
class SignOutErrorState extends TimeLuxeStates {
final String error;
SignOutErrorState(this.error);
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation | mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/widgets/time_luxe_app_view_body.dart | import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/core/utils/helper.dart';
import '../../../core/widgets/my_circular_progress_indicator.dart';
class TimeLuxeAppViewBody extends StatelessWidget {
const TimeLuxeAppViewBody({
super.key,
required this.cubit,
required this.state,
});
final TimeLuxeCubit cubit;
final TimeLuxeStates state;
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
if (cubit.currentIndex != 0) {
cubit.changeBottomNavToHome();
return Future.value(false);
}
return Future.value(true);
},
child: ConditionalBuilder(
condition: Helper.model != null,
builder: (context) => cubit.body[cubit.currentIndex],
fallback: (context) => const MyCircularProgressIndicator(),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation | mirrored_repositories/TimeLuxe/lib/TimeLuxe/presentation/widgets/bottom_nav_bar.dart | import 'package:flutter/material.dart';
import '../../../core/global/app_colors.dart';
import '../../../core/global/app_text_styles.dart';
import '../view/manager/time_luxe_cubit.dart';
class BottomNavBar extends StatelessWidget {
const BottomNavBar({
super.key,
required this.cubit,
});
final TimeLuxeCubit cubit;
@override
Widget build(BuildContext context) {
return BottomNavigationBar(
currentIndex: cubit.currentIndex,
onTap: (index) => cubit.changeBottomNavIndex(index),
items: cubit.bottomNavItems,
showSelectedLabels: true,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
selectedItemColor: AppColors.primaryColor,
selectedIconTheme: const IconThemeData(size: 29),
unselectedIconTheme: const IconThemeData(size: 24),
selectedLabelStyle: AppTextStyles.textStyle18
.copyWith(fontWeight: FontWeight.w600, color: AppColors.primaryColor),
unselectedLabelStyle: AppTextStyles.textStyle18.copyWith(
fontWeight: FontWeight.w600,
color: Colors.black,
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/TimeLuxe | mirrored_repositories/TimeLuxe/lib/TimeLuxe/domain/time_luxe_repo.dart | import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import '../../core/models/user_model.dart';
abstract class TimeLuxeRepo {
Future<DocumentSnapshot<Map<String, dynamic>>> getUserData(String? uId);
Future<void> updateUser({required UserModel userModel});
Future<XFile?> getProfileImage({required ImageSource source});
Future<TaskSnapshot> uploadProfileImage({File? profileImage});
Future<void> signOut();
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/bag/presentation | mirrored_repositories/TimeLuxe/lib/features/bag/presentation/widgets/brand_name.dart | import 'package:flutter/material.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/features/bag/presentation/widgets/done_square.dart';
import '../../../../core/global/app_text_styles.dart';
class BrandName extends StatefulWidget {
const BrandName({
super.key,
});
@override
State<BrandName> createState() => _BrandNameState();
}
class _BrandNameState extends State<BrandName> {
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
const DoneSquare(),
SizedBox(width: SizeConfig.screenWidth! * 0.039),
Text(
"rolex".toUpperCase(),
style: AppTextStyles.textStyle18.copyWith(
fontWeight: FontWeight.w600,
),
),
],
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/bag/presentation | mirrored_repositories/TimeLuxe/lib/features/bag/presentation/widgets/bag_products_list.dart | import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/widgets/fall_back_text.dart';
import '../../../../TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import '../../../../core/global/app_constants.dart';
import 'brand_name.dart';
import 'order_item.dart';
class BagProductsList extends StatelessWidget {
const BagProductsList({
super.key,
required this.cubit,
});
final TimeLuxeCubit cubit;
@override
Widget build(BuildContext context) {
return ConditionalBuilder(
condition: AppConstants.bagItems.isNotEmpty,
builder: (context) => Padding(
padding: EdgeInsets.only(bottom: 20.h),
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const BrandName(),
SizedBox(height: SizeConfig.screenHeight! * 0.032),
Column(
children: List.generate(
AppConstants.bagItems.length,
(index) => Padding(
padding: EdgeInsets.only(bottom: 10.h),
child: OrderItem(
cubit: cubit,
bagProduct: AppConstants.bagItems[index],
index: index,
),
),
),
),
],
),
),
fallback: (context) => const FallBackText(
text: "No products in the Bag yet,\nExplore products to add one",
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/bag/presentation | mirrored_repositories/TimeLuxe/lib/features/bag/presentation/widgets/bag_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/core/global/app_text_styles.dart';
import 'package:time_luxe/core/widgets/custom_app_bar.dart';
import 'package:time_luxe/features/bag/presentation/widgets/done_square.dart';
import 'package:time_luxe/features/check_out/presentation/views/check_out_view.dart';
import 'package:time_luxe/features/favorites/presentation/views/favorites_view.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/widgets/customized_divider.dart';
import 'bag_products_list.dart';
class BagViewBody extends StatelessWidget {
const BagViewBody({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TimeLuxeCubit, TimeLuxeStates>(
builder: (context, state) {
TimeLuxeCubit cubit = TimeLuxeCubit.getObject(context);
String totalPrice =
cubit.countAllBagPrices().toStringAsFixed(1).toString();
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
padding: EdgeInsets.only(top: 24.h),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: SizeConfig.screenHeight! * 0.05),
CustomAppBar(
padding: EdgeInsets.only(left: 24.w, right: 48.w),
title: "Bag",
actions: GestureDetector(
onTap: () => CustomNavigator.navigateTo(
screen: () => const FavoritesView(),
),
child: const Icon(
Icons.favorite_border,
color: Colors.white,
),
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.016),
const CustomizedDivider(),
SizedBox(height: SizeConfig.screenHeight! * 0.039),
BagProductsList(cubit: cubit),
SizedBox(height: SizeConfig.screenHeight! * 0.02),
Padding(
padding: EdgeInsets.only(right: 15.w),
child: Row(
children: <Widget>[
const DoneSquare(),
SizedBox(width: SizeConfig.screenWidth! * 0.039),
Text(
"Choose all",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w500,
),
),
const Spacer(),
Text(
"\$$totalPrice",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w500,
),
),
],
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.029),
Center(
child: Padding(
padding: EdgeInsets.only(bottom: 16.h),
child: MyCustomButton(
height: 49.h,
width: SizeConfig.screenWidth! * 0.9,
radius: 8.r,
onPressed: () => CustomNavigator.navigateTo(
screen: () => CheckOutView(subtotal: totalPrice),
),
hasPrefix: false,
backgroundColor: AppColors.primaryColor,
child: Center(
child: Text(
"Checkout",
style: AppTextStyles.textStyle32.copyWith(
fontSize: 23.sp,
),
),
),
),
),
),
],
),
),
),
);
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/bag/presentation | mirrored_repositories/TimeLuxe/lib/features/bag/presentation/widgets/order_item.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/features/product_details/presentation/views/product_details_view.dart';
import '../../../../TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
import '../../../../core/models/watch_model.dart';
import 'done_square.dart';
class OrderItem extends StatelessWidget {
const OrderItem({
super.key,
required this.cubit,
required this.bagProduct,
required this.index,
});
final TimeLuxeCubit cubit;
final WatchModel bagProduct;
final int index;
@override
Widget build(BuildContext context) {
return Slidable(
key: const ValueKey(0),
endActionPane: ActionPane(
motion: const ScrollMotion(),
children: <Widget>[
Container(
height: 70.h,
width: 66.w,
color: const Color(0xFF74d592),
child: GestureDetector(
onTap: () => cubit.removeBagProduct(bagProduct),
child: Icon(
FontAwesomeIcons.solidTrashCan,
color: Colors.red,
size: 25.w,
),
),
),
],
),
child: Padding(
padding: EdgeInsets.only(right: 15.w),
child: Row(
children: <Widget>[
const DoneSquare(),
SizedBox(width: SizeConfig.screenWidth! * 0.039),
SizedBox(
height: 70.h,
width: 50.w,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10.r)),
child: GestureDetector(
onTap: () => CustomNavigator.navigateTo(
screen: () => ProductDetailsView(model: bagProduct),
),
child: Hero(
tag: bagProduct.id!,
child: Image.asset(bagProduct.image!),
),
),
),
),
const Spacer(flex: 1),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
bagProduct.name ?? "No Name",
style: AppTextStyles.textStyle12,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
"Color: ${(bagProduct.color) ?? "No Color"}",
style: AppTextStyles.textStyle12.copyWith(
fontSize: 10.sp,
fontWeight: FontWeight.normal,
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.005),
Text(
"\$${(bagProduct.price) ?? "No Price"}",
style: AppTextStyles.textStyle12,
),
],
),
const Spacer(flex: 4),
GestureDetector(
onTap: () => cubit.decrement(),
child: Container(
height: 22.w,
width: 22.w,
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(color: Colors.white, width: 3),
),
child: Icon(
Icons.remove,
color: Colors.white,
size: 15.w,
),
),
),
SizedBox(width: SizeConfig.screenWidth! * 0.022),
Text(
"${cubit.ordersCounter}",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
SizedBox(width: SizeConfig.screenWidth! * 0.022),
GestureDetector(
onTap: () => cubit.increment(),
child: Icon(
Icons.add_box,
color: AppColors.primaryColor,
size: 33.w,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/bag/presentation | mirrored_repositories/TimeLuxe/lib/features/bag/presentation/widgets/done_square.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../../../core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
class DoneSquare extends StatefulWidget {
const DoneSquare({super.key});
@override
State<DoneSquare> createState() => _DoneSquareState();
}
class _DoneSquareState extends State<DoneSquare> {
Widget? child;
Color backgroundColor = Colors.white;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
if (child == null) {
child = SvgPicture.asset(AppAssets.done);
backgroundColor = AppColors.primaryColor;
} else {
child = null;
backgroundColor = Colors.white;
}
});
},
child: Container(
height: 24.w,
width: 24.w,
margin: EdgeInsets.only(left: 22.w),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.all(Radius.circular(5.r)),
),
child: child,
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/notifications/presentation | mirrored_repositories/TimeLuxe/lib/features/notifications/presentation/views/notifications_view.dart | import 'package:flutter/material.dart';
import 'package:time_luxe/features/notifications/presentation/widgets/notifications_view_body.dart';
class NotificationsView extends StatelessWidget {
const NotificationsView({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: NotificationsViewBody(),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/notifications/presentation | mirrored_repositories/TimeLuxe/lib/features/notifications/presentation/widgets/notifications_view_body.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_colors.dart';
import 'package:time_luxe/core/global/app_text_styles.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/time_luxe_app_view.dart';
import '../../../../core/global/app_assets.dart';
class NotificationsViewBody extends StatelessWidget {
const NotificationsViewBody({super.key});
@override
Widget build(BuildContext context) {
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: SizeConfig.screenHeight! * 0.08),
Text(
"Stay in the Loop",
style: AppTextStyles.textStyle32,
),
SizedBox(height: SizeConfig.screenHeight! * 0.015),
Padding(
padding: EdgeInsets.symmetric(horizontal: 8.w),
child: Text(
"We'll send notifications to keep you updated on your orders",
style: AppTextStyles.textStyle15,
textAlign: TextAlign.center,
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.08),
SvgPicture.asset(AppAssets.group1),
SizedBox(height: SizeConfig.screenHeight! * 0.1),
MyCustomButton(
width: 320.w,
height: 49.h,
radius: 14.r,
backgroundColor: AppColors.darkGreen,
onPressed: () {
CustomHelper.buildSnackBar(
context: context,
message: "Notifications are turned on",
state: SnackBarStates.success,
title: "Success",
);
Future.delayed(
const Duration(milliseconds: 400),
() => CustomNavigator.navigateAndFinish(
screen: () => const TimeLuxeAppView(),
),
);
},
hasPrefix: false,
child: Center(
child: Text(
"Turn on Notifications",
style: AppTextStyles.textStyle20.copyWith(
fontSize: 23.sp,
fontWeight: FontWeight.normal,
color: Colors.white,
),
),
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.015),
MyCustomButton(
width: 320.w,
height: 49.h,
radius: 14.r,
backgroundColor: Colors.transparent,
border: Border.all(
color: Colors.white,
width: 2,
),
onPressed: () => CustomNavigator.navigateAndFinish(
screen: () => const TimeLuxeAppView(),
),
hasPrefix: false,
child: Center(
child: Text(
"Not Now",
style: AppTextStyles.textStyle20.copyWith(
fontSize: 23.sp,
fontWeight: FontWeight.normal,
color: AppColors.darkGreen,
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/views/check_out_view.dart | import 'package:flutter/material.dart';
import 'package:time_luxe/features/check_out/presentation/widgets/check_out_view_body.dart';
class CheckOutView extends StatelessWidget {
const CheckOutView({super.key, required this.subtotal});
final String subtotal;
@override
Widget build(BuildContext context) {
return Scaffold(
body: CheckOutViewBody(subtotal: subtotal),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/views/my_card_view.dart | import 'package:flutter/material.dart';
import 'package:time_luxe/features/check_out/presentation/widgets/my_card_view_body.dart';
class MyCardView extends StatelessWidget {
const MyCardView({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: MyCardViewBody(),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/my_card_form.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
class MyCardForm extends StatefulWidget {
const MyCardForm({super.key});
@override
State<MyCardForm> createState() => _MyCardFormState();
}
class _MyCardFormState extends State<MyCardForm> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController cardNumberController = TextEditingController();
final TextEditingController expirationDateController =
TextEditingController();
final TextEditingController cardHolderController = TextEditingController();
final TextEditingController cvvNumberController = TextEditingController();
@override
void dispose() {
disposeControllers();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(bottom: 12.h),
child: CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: "Enter Card Number",
hintStyle: AppTextStyles.textStyle16.copyWith(
color: AppColors.hintColor,
fontWeight: FontWeight.w600,
),
controller: cardNumberController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.number,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 1,
enabledBorderColor: Colors.white,
enabledBorderWidth: 1,
),
),
Padding(
padding: EdgeInsets.only(bottom: 12.h),
child: CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: "Expiration Date",
hintStyle: AppTextStyles.textStyle16.copyWith(
color: AppColors.hintColor,
fontWeight: FontWeight.w600,
),
controller: expirationDateController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.datetime,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 1,
enabledBorderColor: Colors.white,
enabledBorderWidth: 1,
),
),
Padding(
padding: EdgeInsets.only(bottom: 12.h),
child: CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: "Cardholder Now",
hintStyle: AppTextStyles.textStyle16.copyWith(
color: AppColors.hintColor,
fontWeight: FontWeight.w600,
),
controller: cardHolderController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.datetime,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 1,
enabledBorderColor: Colors.white,
enabledBorderWidth: 1,
),
),
Padding(
padding: EdgeInsets.only(bottom: 12.h),
child: CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: "Cvv Number",
hintStyle: AppTextStyles.textStyle16.copyWith(
color: AppColors.hintColor,
fontWeight: FontWeight.w600,
),
controller: cvvNumberController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.datetime,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 1,
enabledBorderColor: Colors.white,
enabledBorderWidth: 1,
),
),
],
),
),
);
}
void disposeControllers() {
cardHolderController.dispose();
expirationDateController.dispose();
cardHolderController.dispose();
cvvNumberController.dispose();
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/payment_method.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/features/check_out/presentation/views/my_card_view.dart';
class PaymentMethod extends StatefulWidget {
const PaymentMethod({super.key, required this.methodLogo});
final String methodLogo;
@override
State<PaymentMethod> createState() => _PaymentMethodState();
}
class _PaymentMethodState extends State<PaymentMethod> {
Color borderColor = Colors.transparent;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
if (borderColor != Colors.red) {
setState(() {
borderColor = Colors.red;
});
Future.delayed(const Duration(milliseconds: 700), () {
CustomNavigator.navigateTo(screen: () => const MyCardView());
setState(() {
borderColor = Colors.transparent;
});
});
} else {
setState(() {
borderColor = Colors.transparent;
});
}
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8.r)),
border: Border.all(
color: borderColor,
width: borderColor == Colors.red ? 3 : 0,
),
),
child: SvgPicture.asset(widget.methodLogo),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/my_card_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_assets.dart';
import 'package:time_luxe/features/check_out/presentation/widgets/my_card_form.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
import '../../../../core/widgets/customized_divider.dart';
import 'checkout_app_bar.dart';
class MyCardViewBody extends StatelessWidget {
const MyCardViewBody({super.key});
@override
Widget build(BuildContext context) {
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
children: <Widget>[
const CheckoutAppBar(title: 'My Card'),
const CustomizedDivider(),
SizedBox(height: SizeConfig.screenHeight! * 0.025),
Image.asset(AppAssets.visaCard),
SizedBox(height: SizeConfig.screenHeight! * 0.032),
const MyCardForm(),
SizedBox(height: SizeConfig.screenHeight! * 0.025),
Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: MyCustomButton(
height: 49.h,
width: SizeConfig.screenWidth! * 0.9,
backgroundColor: AppColors.primaryColor,
radius: 8.r,
onPressed: () {},
hasPrefix: false,
child: Center(
child: Text(
"Pay Now",
style: AppTextStyles.textStyle27.copyWith(
fontSize: 23.sp,
),
),
),
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.035),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/checkout_app_bar.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:reusable_components/reusable_components.dart';
import '../../../../core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
class CheckoutAppBar extends StatelessWidget {
const CheckoutAppBar({
super.key,
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(
top: SizeConfig.screenHeight! * 0.07,
bottom: SizeConfig.screenHeight! * 0.02,
),
child: Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 50.w),
child: IconButton(
padding: EdgeInsets.zero,
icon: SvgPicture.asset(
AppAssets.back,
color: AppColors.primaryColor,
),
onPressed: () => CustomNavigator.getBack(),
),
),
SizedBox(width: SizeConfig.screenWidth! * 0.1),
Expanded(
child: Text(
title,
style: AppTextStyles.textStyle32.copyWith(
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/payment_methods.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../../core/global/app_assets.dart';
import '/features/check_out/presentation/widgets/payment_method.dart';
class PaymentMethods extends StatelessWidget {
const PaymentMethods({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: const Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
PaymentMethod(methodLogo: AppAssets.mastercard),
PaymentMethod(methodLogo: AppAssets.visa),
PaymentMethod(methodLogo: AppAssets.paypal),
],
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/new_card_text_field.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
class NewCardTextField extends StatefulWidget {
const NewCardTextField({
super.key,
});
@override
State<NewCardTextField> createState() => _NewCardTextFieldState();
}
class _NewCardTextFieldState extends State<NewCardTextField> {
final TextEditingController textEditingController = TextEditingController();
@override
void dispose() {
textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: "Or add a new card",
hintStyle: AppTextStyles.textStyle16.copyWith(
color: AppColors.hintColor,
fontWeight: FontWeight.w600,
),
prefixIcon: Icon(
Icons.add,
color: AppColors.hintColor,
),
controller: textEditingController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.text,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 1,
enabledBorderColor: Colors.white,
enabledBorderWidth: 1,
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/check_out/presentation | mirrored_repositories/TimeLuxe/lib/features/check_out/presentation/widgets/check_out_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_text_styles.dart';
import '../../../../core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/widgets/customized_divider.dart';
import 'checkout_app_bar.dart';
import 'new_card_text_field.dart';
import 'payment_methods.dart';
class CheckOutViewBody extends StatelessWidget {
const CheckOutViewBody({super.key, required this.subtotal});
final String subtotal;
@override
Widget build(BuildContext context) {
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const CheckoutAppBar(title: 'Checkout'),
const CustomizedDivider(),
Padding(
padding: EdgeInsets.only(
left: 18.w,
top: 34.h,
bottom: 50.h,
),
child: Text(
"Select Your Payment Method",
style: AppTextStyles.textStyle24.copyWith(
fontWeight: FontWeight.w500,
),
),
),
const PaymentMethods(),
SizedBox(height: SizeConfig.screenHeight! * 0.055),
Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: Image.asset(AppAssets.checkoutImage),
),
SizedBox(height: SizeConfig.screenHeight! * 0.055),
const NewCardTextField(),
SizedBox(height: SizeConfig.screenHeight! * 0.017),
Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: AppTextStyles.textStyle27.copyWith(
fontSize: 23.sp,
),
),
Text(
"\$$subtotal",
style: AppTextStyles.textStyle15.copyWith(
color: AppColors.primaryColor,
fontWeight: FontWeight.w900,
),
),
],
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.065),
Padding(
padding: EdgeInsets.symmetric(horizontal: 18.w),
child: MyCustomButton(
height: 49.h,
width: SizeConfig.screenWidth! * 0.9,
backgroundColor: AppColors.primaryColor,
radius: 8.r,
onPressed: () {},
hasPrefix: false,
child: Center(
child: Text(
"Buy Now",
style: AppTextStyles.textStyle27.copyWith(
fontSize: 23.sp,
),
),
),
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.035),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/favorites/presentation | mirrored_repositories/TimeLuxe/lib/features/favorites/presentation/views/favorites_view.dart | import 'package:flutter/material.dart';
import 'package:time_luxe/features/favorites/presentation/widgets/favorites_view_body.dart';
class FavoritesView extends StatelessWidget {
const FavoritesView({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: FavoritesViewBody(),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/favorites/presentation | mirrored_repositories/TimeLuxe/lib/features/favorites/presentation/widgets/favorites_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/widgets/fall_back_text.dart';
import '../../../../core/widgets/search_text_field.dart';
import 'fav_item.dart';
class FavoritesViewBody extends StatelessWidget {
const FavoritesViewBody({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TimeLuxeCubit, TimeLuxeStates>(
builder: (context, state) {
TimeLuxeCubit cubit = TimeLuxeCubit.getObject(context);
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
padding: EdgeInsets.symmetric(vertical: 24.h),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
children: <Widget>[
SizedBox(height: SizeConfig.screenHeight! * 0.05),
SearchTextField(
onTap: () {},
hint: "Favorites",
),
SizedBox(height: SizeConfig.screenHeight! * 0.06),
ConditionalBuilder(
condition: cubit.favorites.isNotEmpty,
builder: (context) => ListView.separated(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) => FavItem(
favItem: cubit.favorites[index],
cubit: cubit,
),
separatorBuilder: (context, index) =>
SizedBox(height: SizeConfig.screenHeight! * 0.064),
itemCount: cubit.favorites.length,
),
fallback: (context) => const FallBackText(
text:
"No products in the Favorites yet,\nExplore products to add one",
),
),
],
),
),
),
);
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/favorites/presentation | mirrored_repositories/TimeLuxe/lib/features/favorites/presentation/widgets/fav_item.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_constants.dart';
import '../../../../TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
import '../../../../core/models/watch_model.dart';
import '../../../product_details/presentation/views/product_details_view.dart';
class FavItem extends StatelessWidget {
const FavItem({
super.key,
required this.favItem,
required this.cubit,
});
final WatchModel favItem;
final TimeLuxeCubit cubit;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 16.w),
child: Row(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(25.r)),
child: GestureDetector(
onTap: () => CustomNavigator.navigateTo(
screen: () => ProductDetailsView(model: favItem),
),
child: Hero(
tag: favItem.id!,
child: Image.asset(
favItem.image!,
fit: BoxFit.cover,
height: 132.h,
width: 139.w,
),
),
),
),
const Spacer(flex: 1),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
favItem.name!,
style: AppTextStyles.textStyle24.copyWith(
fontWeight: FontWeight.w900,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: SizeConfig.screenHeight! * 0.016),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
"\$${favItem.price!}",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w900, color: Colors.white),
),
SizedBox(width: SizeConfig.screenWidth! * 0.055),
GestureDetector(
onTap: () {
if (AppConstants.bagItems
.any((element) => element == favItem)) {
cubit.removeBagProduct(favItem);
} else {
cubit.addToBag(favItem);
}
},
child: Icon(
Icons.shopping_cart_rounded,
color: AppConstants.bagItems
.any((element) => element == favItem)
? AppColors.primaryColor
: Colors.white,
),
),
SizedBox(width: SizeConfig.screenWidth! * 0.02),
GestureDetector(
onTap: () => cubit.removeFromFav(favItem),
child: const Icon(
Icons.favorite,
color: AppColors.primaryColor,
),
),
],
),
],
),
const Spacer(flex: 2),
],
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/views/edit_profile_view.dart | import 'package:flutter/material.dart';
import 'package:time_luxe/features/profile/presentation/widgets/edit_profile_view_body.dart';
class EditProfileView extends StatelessWidget {
const EditProfileView({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: EditProfileViewBody(),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/edit_profile_image.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/models/user_model.dart';
import '../../../../core/utils/helper.dart';
class EditProfileImage extends StatelessWidget {
const EditProfileImage({
Key? key,
required this.profileImage,
required this.userModel,
required this.cubit,
}) : super(key: key);
final File? profileImage;
final UserModel userModel;
final TimeLuxeCubit cubit;
@override
Widget build(BuildContext context) {
return Stack(
alignment: AlignmentDirectional.bottomEnd,
children: <Widget>[
CircleAvatar(
backgroundColor: AppColors.primaryColor,
radius: 110.r,
backgroundImage: (profileImage == null
? NetworkImage(userModel.image!)
: FileImage(profileImage!)) as ImageProvider,
),
Padding(
padding: EdgeInsets.only(bottom: 8.0.h),
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 28.r,
child: GestureDetector(
onTap: () => Helper.buildBottomSheet(
type: "Profile",
context: context,
onPressedCamera: () => cubit.getProfileImage(
source: ImageSource.camera,
),
onPressedGallery: () => cubit.getProfileImage(
source: ImageSource.gallery,
),
),
child: SvgPicture.asset(
AppAssets.cameraIcon,
color: const Color(0xFF0FA958),
height: 35.h,
width: 35.h,
),
),
),
),
],
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/current_user_info.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_assets.dart';
import 'package:time_luxe/features/profile/presentation/views/edit_profile_view.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
import '../../../../core/models/user_model.dart';
class CurrentUserInfo extends StatelessWidget {
const CurrentUserInfo({
super.key,
required this.user,
});
final UserModel user;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 20.w),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
CircleAvatar(
radius: 45.r,
backgroundImage: NetworkImage(user.image!),
backgroundColor: AppColors.primaryColor,
),
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
userName(),
style: AppTextStyles.textStyle24.copyWith(
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
user.email!,
style: AppTextStyles.textStyle13,
),
],
),
const Spacer(flex: 2),
GestureDetector(
onTap: () => CustomNavigator.navigateTo(
screen: () => const EditProfileView(),
),
child: SvgPicture.asset(
AppAssets.edit,
color: Colors.white,
),
),
],
),
);
}
String userName() {
if (user.name!.length > 11) {
return "${user.name!.substring(0, 11)}..";
} else {
return user.name!;
}
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/user_service.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:reusable_components/reusable_components.dart';
import '../../../../core/global/app_text_styles.dart';
class UserService extends StatelessWidget {
const UserService({
super.key,
required this.title,
required this.icon,
required this.onTap,
});
final String title;
final String icon;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
GestureDetector(
onTap: onTap,
child: SvgPicture.asset(
icon,
color: Colors.white,
height: 44.w,
width: 44.w,
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.007),
Text(
title,
style: AppTextStyles.textStyle16.copyWith(
color: Colors.white,
),
),
],
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/settings_title.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../../core/global/app_text_styles.dart';
class SettingsTitle extends StatelessWidget {
const SettingsTitle({
super.key,
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 16.w),
child: Text(
title,
style: AppTextStyles.textStyle24.copyWith(
fontWeight: FontWeight.w600,
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/edit_profile_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/core/global/app_text_styles.dart';
import 'package:time_luxe/features/profile/presentation/widgets/edit_profile_image.dart';
import 'package:time_luxe/features/profile/presentation/widgets/update_user_form.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/models/user_model.dart';
import '../../../../core/utils/helper.dart';
import '../../../../core/widgets/my_circular_progress_indicator.dart';
import 'confirm_editing_profile_image.dart';
class EditProfileViewBody extends StatelessWidget {
const EditProfileViewBody({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TimeLuxeCubit, TimeLuxeStates>(
builder: (context, state) {
TimeLuxeCubit cubit = TimeLuxeCubit.getObject(context);
UserModel userModel = Helper.model!;
final TextEditingController nameController = TextEditingController();
final TextEditingController emailController = TextEditingController();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
nameController.text = userModel.name!;
emailController.text = userModel.email!;
return Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
children: <Widget>[
SizedBox(height: SizeConfig.screenHeight! * 0.15),
EditProfileImage(
profileImage: cubit.profileImage,
userModel: userModel,
cubit: cubit,
),
if (cubit.profileImage != null) ...[
SizedBox(height: SizeConfig.screenHeight! * 0.015),
ConfirmEditingProfileImage(
state: state,
cubit: cubit,
nameController: nameController,
emailController: emailController,
),
],
SizedBox(height: SizeConfig.screenHeight! * 0.1),
UpdateUserForm(
formKey: formKey,
nameController: nameController,
emailController: emailController,
),
SizedBox(height: SizeConfig.screenHeight! * 0.12),
ConditionalBuilder(
condition: state is! UserUpdateLoadingState,
builder: (context) => Padding(
padding: EdgeInsets.symmetric(horizontal: 28.w),
child: MyCustomButton(
height: 49.h,
radius: 14.r,
width: SizeConfig.screenWidth! * 0.9,
backgroundColor: AppColors.primaryColor,
onPressed: () {
cubit.updateUser(
name: nameController.text,
email: emailController.text,
);
CustomHelper.buildSnackBar(
context: context,
message: "User updated successfully",
state: SnackBarStates.success,
title: "Success",
);
},
hasPrefix: false,
child: Center(
child: Text(
"Update",
style: AppTextStyles.textStyle32.copyWith(
color: Colors.white,
fontWeight: FontWeight.w900,
),
),
),
),
),
fallback: (context) => const MyCircularProgressIndicator(),
),
SizedBox(height: SizeConfig.screenHeight! * 0.04),
],
),
),
),
);
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/sign_out_floating_button.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
class SignOutFloatingButton extends StatelessWidget {
const SignOutFloatingButton({
Key? key,
required this.cubit,
}) : super(key: key);
final TimeLuxeCubit cubit;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0.h,
horizontal: 5.0.w,
),
child: FloatingActionButton(
heroTag: "Floating Sign Out Button",
backgroundColor: Colors.redAccent,
onPressed: () => cubit.signOut(),
child: Icon(
Icons.logout_rounded,
color: Colors.white,
size: 22.w,
),
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/other_settings.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import '../../../../core/global/app_text_styles.dart';
class OtherSettings extends StatelessWidget {
const OtherSettings({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(
left: 54.w,
top: SizeConfig.screenHeight! * 0.01,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Contact Preferences",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w600,
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.01),
Text(
"Terms & Conditions ",
style: AppTextStyles.textStyle20.copyWith(
fontWeight: FontWeight.w600,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/profile_view_body.dart | import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import 'package:time_luxe/core/models/user_model.dart';
import 'package:time_luxe/features/profile/presentation/widgets/sign_out_floating_button.dart';
import '../../../../core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/utils/helper.dart';
import '../../../../core/widgets/customized_divider.dart';
import 'current_user_info.dart';
import 'general_settings.dart';
import '../../../../core/widgets/custom_app_bar.dart';
import 'other_settings.dart';
import 'settings_title.dart';
import 'user_services.dart';
class ProfileViewBody extends StatelessWidget {
const ProfileViewBody({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TimeLuxeCubit, TimeLuxeStates>(
builder: (context, state) {
TimeLuxeCubit cubit = TimeLuxeCubit.getObject(context);
UserModel user = Helper.model!;
return Stack(
children: <Widget>[
Container(
height: SizeConfig.screenHeight,
width: SizeConfig.screenWidth,
padding: EdgeInsets.symmetric(vertical: 22.h),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: AppColors.gradientColors,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
child: FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: SizeConfig.screenHeight! * 0.05),
CustomAppBar(
padding: EdgeInsets.symmetric(horizontal: 16.w),
title: "Profile",
actions: Row(
children: <Widget>[
Icon(
Icons.email_outlined,
size: 35.w,
color: Colors.white,
),
SizedBox(width: SizeConfig.screenWidth! * 0.05),
SvgPicture.asset(
AppAssets.profileNotificationsIcon,
color: AppColors.primaryColor,
),
],
),
),
SizedBox(height: SizeConfig.screenHeight! * 0.02),
const CustomizedDivider(),
SizedBox(height: SizeConfig.screenHeight! * 0.025),
CurrentUserInfo(user: user),
SizedBox(height: SizeConfig.screenHeight! * 0.02),
const UserServices(),
SizedBox(height: SizeConfig.screenHeight! * 0.006),
const SettingsTitle(title: "General Settings"),
const GeneralSettings(),
const SettingsTitle(title: "Other"),
const OtherSettings(),
],
),
),
),
),
FadeInUp(
from: 20,
duration: const Duration(milliseconds: 500),
child: Align(
alignment: AlignmentDirectional.bottomEnd,
child: SignOutFloatingButton(cubit: cubit),
),
),
],
);
});
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/confirm_editing_profile_image.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/TimeLuxe/presentation/view/manager/time_luxe_cubit.dart';
import '../../../../TimeLuxe/presentation/view/manager/time_luxe_states.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
class ConfirmEditingProfileImage extends StatelessWidget {
const ConfirmEditingProfileImage({
super.key,
required this.state,
required this.cubit,
required this.nameController,
required this.emailController,
});
final TimeLuxeStates state;
final TimeLuxeCubit cubit;
final TextEditingController nameController;
final TextEditingController emailController;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
MyCustomButton(
radius: 32.r,
height: 40.h,
width: SizeConfig.screenWidth! * 0.5,
backgroundColor: AppColors.primaryColor,
onPressed: () => cubit.uploadProfileImage(
context: context,
name: nameController.text,
email: emailController.text,
),
hasPrefix: false,
child: Center(
child: Text(
"Update Profile Image",
style: AppTextStyles.textStyle16.copyWith(
fontWeight: FontWeight.w900,
color: Colors.white,
),
),
),
),
if (state is UploadingProfileImageLoadingState)
SizedBox(height: SizeConfig.screenHeight! * 0.01),
if (state is UploadingProfileImageLoadingState)
SizedBox(
width: SizeConfig.screenWidth! * 0.4,
child: const LinearProgressIndicator(
color: AppColors.primaryColor,
backgroundColor: Colors.transparent,
),
),
],
);
}
}
| 0 |
mirrored_repositories/TimeLuxe/lib/features/profile/presentation | mirrored_repositories/TimeLuxe/lib/features/profile/presentation/widgets/update_user_form.dart | import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:reusable_components/reusable_components.dart';
import 'package:time_luxe/core/global/app_assets.dart';
import '../../../../core/global/app_colors.dart';
import '../../../../core/global/app_text_styles.dart';
class UpdateUserForm extends StatelessWidget {
const UpdateUserForm({
super.key,
required this.nameController,
required this.emailController,
required this.formKey,
});
final TextEditingController nameController;
final TextEditingController emailController;
final GlobalKey<FormState> formKey;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 28.w),
child: Form(
key: formKey,
child: Column(
children: <Widget>[
CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: nameController.text,
controller: nameController,
textCapitalization: TextCapitalization.words,
keyboardType: TextInputType.name,
cursorColor: AppColors.primaryColor,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 2,
enabledBorderColor: Colors.white,
enabledBorderWidth: 2,
style: AppTextStyles.textStyle24.copyWith(
color: Colors.black,
fontWeight: FontWeight.w600,
),
hintStyle: AppTextStyles.textStyle24.copyWith(
color: Colors.black,
fontWeight: FontWeight.w600,
),
prefixIcon: Padding(
padding: EdgeInsets.only(left: 14.w, right: 50.w),
child: SvgPicture.asset(AppAssets.iconsPersonIcon),
),
validating: (String? val) {
if (val!.isEmpty) {
return "Name can't be blank!";
}
return null;
},
),
SizedBox(height: SizeConfig.screenHeight! * 0.04),
CustomTextFormField(
backgroundColor: Colors.white.withOpacity(0),
hint: emailController.text,
controller: emailController,
textCapitalization: TextCapitalization.none,
keyboardType: TextInputType.emailAddress,
cursorColor: AppColors.primaryColor,
focusedBorderColor: AppColors.primaryColor,
focusedBorderWidth: 2,
enabledBorderColor: Colors.white,
enabledBorderWidth: 2,
style: AppTextStyles.textStyle24.copyWith(
color: Colors.black,
fontWeight: FontWeight.w600,
),
hintStyle: AppTextStyles.textStyle24.copyWith(
color: Colors.black,
fontWeight: FontWeight.w600,
),
prefixIcon: Padding(
padding: EdgeInsets.only(left: 14.w, right: 50.w),
child: SvgPicture.asset(AppAssets.iconsDashiconsEmailAlt),
),
validating: (String? val) {
if (val!.isEmpty) {
return "Email can't be blank!";
}
return null;
},
),
],
),
),
);
}
}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.