repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/stories-app/lib/ui/global
|
mirrored_repositories/stories-app/lib/ui/global/bloc/global_state.dart
|
part of 'global_bloc.dart';
enum GlobalStatus {
loading,
success,
fail,
}
class GlobalState extends Equatable {
final GlobalStatus? topUsersStatus;
final List<User> topUsers;
@override
List<Object?> get props => [
topUsersStatus,
topUsers,
];
const GlobalState({
this.topUsersStatus,
this.topUsers = const [],
});
GlobalState copyWith({
GlobalStatus? topUsersStatus,
List<User>? topUsers,
}) {
return GlobalState(
topUsersStatus: topUsersStatus ?? this.topUsersStatus,
topUsers: topUsers ?? this.topUsers,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/profile/user_stories_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/loading.dart';
import 'package:jokes_app/ui/profile/bloc/user_stories/user_stories_bloc.dart';
import 'package:jokes_app/ui/profile/bloc/user_stories/user_stories_state.dart';
import '../../common/resource/colors.dart';
import '../../common/resource/decorations.dart';
import '../../common/widgets/not_found.dart';
import '../../common/widgets/story_item.dart';
import '../../di/app_di.dart';
import '../../generated/locale_keys.g.dart';
import '../stories/story_category_item.dart';
import '../view_story/view_story_screen.dart';
import 'bloc/user_stories/user_stories_event.dart';
class UserStoriesScreen extends StatefulWidget {
final int userId;
final String username;
const UserStoriesScreen({
super.key,
required this.userId,
required this.username,
});
@override
State<UserStoriesScreen> createState() => _UserStoriesScreenState();
}
class _UserStoriesScreenState extends State<UserStoriesScreen> {
var selectedCategoryIndex = 0;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => UserStoriesBloc(injector.get())
..add(
SetUserId(id: widget.userId),
)
..add(
GetCategories(
userId: widget.userId,
),
),
child: BlocBuilder<UserStoriesBloc, UserStoriesState>(
builder: (context, state) {
final bloc = context.read<UserStoriesBloc>();
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
title: Text(
"${Strings.stories} ${widget.username}",
style:
primaryTextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
bottom: (state.showCategories && state.categories.isNotEmpty)
? PreferredSize(
preferredSize: Size(context.width, 42),
child: Expanded(
child: ListView.builder(
itemCount: state.categories.length,
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemBuilder: (e, i) {
final item = (state.categories)[i];
return StoryCategoryItem(
value: item,
selected: selectedCategoryIndex == i,
onTap: () {
bloc.add(GetCategoryStories(
categoryId: item.id,
userId: widget.userId));
setState(
() {
selectedCategoryIndex = i;
},
);
},
);
},
),
),
)
: null,
),
body: Container(
height: context.height,
width: context.width,
decoration: const DefaultBackgroundDecoration(),
child: (state.stories.isEmpty)
? state.storiesStatus == UserStoriesStatus.success
? const NotFound()
: const Loading()
: ListView.builder(
padding: const EdgeInsets.only(top: 152),
controller: bloc.scrollController,
physics: const BouncingScrollPhysics(),
itemCount: state.stories.length,
itemBuilder: (e, i) {
final item = (state.stories)[i];
return StoryItem(
onTap: () {
context.navigateTo(
ViewStoryScreen(
story: item,
onReadFinish: () {
bloc.add(SetAsRead(storyId: item.id));
},
onUnpublish: () {
// bloc.add(Un)
},
),
);
},
story: item,
onTapOwner: () {
//
},
);
},
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/profile/profile_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/decorations.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/settings_item.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/common/dialog/about.dart';
import 'package:jokes_app/ui/common/dialog/logout.dart';
import 'package:jokes_app/ui/profile/bloc/profile/profile_bloc.dart';
import 'package:jokes_app/ui/profile/user_info_card.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:modified_localization/easy_localization.dart';
import 'package:share_plus/share_plus.dart';
import '../../common/resource/constants.dart';
import '../../generated/locale_keys.g.dart';
import '../common/dialog/select_language_dialog.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => ProfileBloc(injector.get())
..add(
GetProfile(),
)
..add(
GetProfileStats(),
),
child: BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
final bloc = context.read<ProfileBloc>();
return Container(
height: context.height,
decoration: const DefaultBackgroundDecoration(),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
SettingsItem(
subText: state.profile?.dateJoined,
margin: const EdgeInsets.all(24),
text: state.profile?.username ?? "",
onTap: () {
showCupertinoModalBottomSheet(
context: context,
builder: (context) {
return LogOutContent(
onPositive: () {
bloc.add(LogOut());
},
);
},
);
},
icon: Icons.person,
),
UserStatisticsCard(
margin: const EdgeInsets.only(left: 24, right: 24),
stats: state.profileStats,
),
SettingsItem(
margin: const EdgeInsets.only(left: 24, right: 24, top: 12),
text: Strings.language,
onTap: () {
showCupertinoModalBottomSheet(
context: context,
builder: (context) {
return SelectLanguage(
onSelect: (lang) {
context.setLocale(lang.locale);
},
);
},
);
},
icon: Icons.language,
),
SettingsItem(
margin: const EdgeInsets.only(left: 24, right: 24, top: 12),
text: Strings.about,
onTap: () {
showCupertinoModalBottomSheet(
context: context,
builder: (context) {
return About(
text: Strings.aboutContent,
);
},
);
},
icon: Icons.info_outlined,
),
SettingsItem(
margin: const EdgeInsets.only(left: 24, right: 24, top: 12),
text: Strings.share,
onTap: () {
Share.share(Constants.appUrl);
},
icon: Icons.share,
),
const Padding(
padding: EdgeInsets.all(16),
),
],
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/profile/user_info_card.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/widgets/icon_text.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/domain/models/ui/profile_stats.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/profile/bloc/profile/profile_bloc.dart';
import 'package:jokes_app/ui/profile/notifications/notifications_screen.dart';
import 'package:jokes_app/ui/profile/user_stories_screen.dart';
import '../../common/resource/colors.dart';
class UserStatisticsCard extends StatelessWidget {
final EdgeInsets? margin;
final double? width;
final double? height;
final ProfileStats? stats;
@override
Widget build(BuildContext context) {
return BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
return Container(
alignment: Alignment.centerLeft,
height: height,
width: width,
margin: margin,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
color: AppColors.primaryDark),
child: Column(
children: [
ScaleTap(
child: IconText(
icon: Icons.favorite,
text: '${Strings.readCount} ${stats?.readStoriesCount ?? ""}',
),
onPressed: () {
//
},
),
ScaleTap(
onPressed: () {
context.navigateTo(UserStoriesScreen(
userId: state.profile?.id ?? -1,
username: state.profile?.username ?? "",
));
},
child: IconText(
hasAction: true,
icon: Icons.pending_actions,
text: '${Strings.published} ${stats?.storyCount ?? ""}',
),
),
ScaleTap(
onPressed: () {},
child: IconText(
icon: Icons.pending_actions,
text:
'${Strings.viewReachCount} ${stats?.viewReachCount ?? ""}',
),
),
ScaleTap(
onPressed: () {
context.navigateTo(const NotificationsScreen());
},
child: IconText(
icon: Icons.notifications,
text:
'${Strings.notifications} ${stats?.unreadNotificationCount ?? ""}',
),
),
],
),
);
},
);
}
const UserStatisticsCard({
super.key,
this.margin,
this.width,
this.height,
required this.stats,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile
|
mirrored_repositories/stories-app/lib/ui/profile/notifications/notifications_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/decorations.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/loading.dart';
import 'package:jokes_app/common/widgets/not_found.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/profile/notifications/bloc/notifications_bloc.dart';
import 'package:jokes_app/ui/profile/notifications/notification_item.dart';
import '../../../common/resource/fonts.dart';
import '../../../generated/locale_keys.g.dart';
class NotificationsScreen extends StatelessWidget {
const NotificationsScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => NotificationsBloc(injector.get())
..add(
GetNotifications(),
),
child: BlocBuilder<NotificationsBloc, NotificationsState>(
builder: (context, state) {
return Scaffold(
appBar: AppBar(
backgroundColor: AppColors.primaryColorBlack,
title: Text(Strings.notifications,
style: primaryTextStyle(
fontSize: 18, fontWeight: FontWeight.bold))),
body: Container(
width: context.width,
height: context.height,
decoration: const DefaultBackgroundDecoration(),
child: state.notifications.isEmpty
? state.notificationStatus == NotificationStatus.success
? const NotFound()
: const Loading()
: ListView.builder(
itemCount: state.notifications.length,
itemBuilder: (e, i) {
return NotificationItem(
notification: state.notifications[i],
onTap: () {
if (!state.notifications[i].isRead) {
context
.read<NotificationsBloc>()
.add(SetRead(id: state.notifications[i].id));
}
},
);
},
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile
|
mirrored_repositories/stories-app/lib/ui/profile/notifications/notification_item.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/common/widgets/story_owner.dart';
import 'package:jokes_app/domain/models/ui/notification.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
class NotificationItem extends StatelessWidget {
final UserNotification notification;
final Function() onTap;
@override
Widget build(BuildContext context) {
return ScaleTap(
onPressed: () {
onTap.call();
},
child: Opacity(
opacity: notification.isRead ? 0.5 : 1,
child: Container(
alignment: Alignment.centerLeft,
padding:
const EdgeInsets.only(left: 12, right: 12, bottom: 12, top: 24),
margin: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
border: Border.all(color: AppColors.whiteAlpha52),
color: AppColors.primaryColor,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
notification.content,
style: primaryTextStyle(),
),
const Padding(
padding: EdgeInsets.all(24),
),
Row(
children: [
if (!notification.isRead)
Flexible(
child: Text(
Strings.tapToMarkAsRead,
style: primaryTextStyle(
color: AppColors.white.withAlpha(152),
),
),
),
const Spacer(),
Container(
margin: const EdgeInsets.only(right: 12),
child: Text(
notification.timeCreate,
style: primaryTextStyle(
color: AppColors.white.withAlpha(152),
),
),
)
],
)
],
),
),
),
);
}
const NotificationItem({
super.key,
required this.notification,
required this.onTap,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/notifications
|
mirrored_repositories/stories-app/lib/ui/profile/notifications/bloc/notifications_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:meta/meta.dart';
import '../../../../domain/models/ui/notification.dart';
import '../../../../domain/repositories/profile_repository.dart';
part 'notifications_event.dart';
part 'notifications_state.dart';
class NotificationsBloc extends Bloc<NotificationsEvent, NotificationsState> {
final ProfileRepository _repository;
NotificationsBloc(
this._repository,
) : super(const NotificationsState()) {
on<GetNotifications>(_getNotifications);
on<SetRead>(_setRead);
}
Future<void> _getNotifications(
GetNotifications event, Emitter emitter) async {
return emitter.forEach(
_repository.getNotifications(),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(notificationStatus: NotificationStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(notificationStatus: NotificationStatus.fail);
}
if (data is DomainSuccess<List<UserNotification>>) {
return state.copyWith(
notificationStatus: NotificationStatus.success,
notifications: data.data);
}
return state;
},
);
}
Future<void> _setRead(SetRead event, Emitter emitter) async {
return emitter.forEach(
_repository.setNotificationRead(event.id),
onData: (data) {
if (data is DomainLoading) {
return state;
}
if (data is DomainFail) {
return state;
}
if (data is DomainSuccess) {
add(GetNotifications());
return state;
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/notifications
|
mirrored_repositories/stories-app/lib/ui/profile/notifications/bloc/notifications_state.dart
|
part of 'notifications_bloc.dart';
enum NotificationStatus {
loading,
success,
fail,
}
@immutable
class NotificationsState extends Equatable {
final NotificationStatus? notificationStatus;
final List<UserNotification> notifications;
@override
List<Object?> get props => [
notificationStatus,
notifications,
];
const NotificationsState({
this.notificationStatus,
this.notifications = const [],
});
NotificationsState copyWith({
NotificationStatus? notificationStatus,
List<UserNotification>? notifications,
}) {
return NotificationsState(
notificationStatus: notificationStatus ?? this.notificationStatus,
notifications: notifications ?? this.notifications,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/notifications
|
mirrored_repositories/stories-app/lib/ui/profile/notifications/bloc/notifications_event.dart
|
part of 'notifications_bloc.dart';
@immutable
abstract class NotificationsEvent {}
class GetNotifications extends NotificationsEvent {}
class SetRead extends NotificationsEvent {
final int id;
SetRead({
required this.id,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/user_stories/user_stories_state.dart
|
import 'package:equatable/equatable.dart';
import 'package:jokes_app/domain/models/ui/story.dart';
import '../../../../domain/models/ui/category.dart';
enum UserStoriesStatus {
loading,
success,
fail,
}
class UserStoriesState extends Equatable {
final UserStoriesStatus? storiesStatus;
final List<Story> stories;
final UserStoriesStatus? categoryStatus;
final List<Category> categories;
final bool showCategories;
final int? categoryId;
final int? userId;
@override
List<Object?> get props => [
storiesStatus,
categoryStatus,
stories,
categories,
showCategories,
categoryId,
userId,
];
const UserStoriesState({
this.storiesStatus,
this.stories = const [],
this.categoryStatus,
this.categories = const [],
this.showCategories = true,
this.categoryId,
this.userId,
});
UserStoriesState copyWith({
UserStoriesStatus? storiesStatus,
List<Story>? stories,
UserStoriesStatus? categoryStatus,
List<Category>? categories,
bool? showCategories,
int? categoryId,
int? userId,
}) {
return UserStoriesState(
storiesStatus: storiesStatus ?? this.storiesStatus,
stories: stories ?? this.stories,
categoryStatus: categoryStatus ?? this.categoryStatus,
categories: categories ?? this.categories,
showCategories: showCategories ?? this.showCategories,
categoryId: categoryId ?? this.categoryId,
userId: userId ?? this.userId,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/user_stories/user_stories_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/common/extensions/controller_ext.dart';
import 'package:jokes_app/ui/profile/bloc/user_stories/user_stories_event.dart';
import 'package:jokes_app/ui/profile/bloc/user_stories/user_stories_state.dart';
import '../../../../domain/models/common/domain_result.dart';
import '../../../../domain/models/ui/category.dart';
import '../../../../domain/models/ui/story.dart';
import '../../../../domain/repositories/profile_repository.dart';
class UserStoriesBloc extends Bloc<UserStoriesEvent, UserStoriesState> {
final ProfileRepository _repository;
final ScrollController scrollController = ScrollController();
int page = 1;
bool endOfPaginationReached = false;
UserStoriesBloc(
this._repository,
) : super(const UserStoriesState()) {
on<GetStories>(_getStories);
on<GetCategories>(_getCategories);
on<GetCategoryStories>(_getCategoryStories);
on<SetUserId>(_setUserId);
on<SetAsRead>(_setAsRead);
//
scrollController.addListener(() {
if (state.showCategories == true) {
emit(state.copyWith(showCategories: false));
}
});
scrollController.onTopReached((onTop) {
emit(state.copyWith(showCategories: onTop));
});
scrollController.onBottomReached(() {
if (!endOfPaginationReached) {
page++;
add(GetStories());
}
});
}
Future<void> _setAsRead(SetAsRead event, Emitter emitter) async {
_repository.setAsRead(event.storyId);
}
Future<void> _getCategoryStories(
GetCategoryStories event, Emitter emitter) async {
page = 1;
emitter(state.copyWith(stories: [], categoryId: event.categoryId));
add(GetStories());
}
Future<void> _setUserId(SetUserId event, Emitter emitter) async {
emitter(state.copyWith(userId: event.id));
}
Future<void> _getStories(GetStories event, Emitter emitter) {
return emitter.forEach(
_repository.getStories(state.userId ?? -1, state.categoryId, page),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(storiesStatus: UserStoriesStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(storiesStatus: UserStoriesStatus.fail);
}
if (data is DomainSuccess<List<Story>>) {
endOfPaginationReached = ((data.data?.length ?? 0) < 10);
return state.copyWith(
storiesStatus: UserStoriesStatus.success,
stories: (state.stories) + (data.data ?? []));
}
return state;
},
);
}
Future<void> _getCategories(GetCategories event, Emitter emitter) {
return emitter.forEach(
_repository.getCategories(event.userId),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(categoryStatus: UserStoriesStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(categoryStatus: UserStoriesStatus.fail);
}
if (data is DomainSuccess<List<Category>>) {
emitter(state.copyWith(categoryId: data.data?.first.id ?? 1));
add(GetStories());
return state.copyWith(
categoryStatus: UserStoriesStatus.success, categories: data.data);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/user_stories/user_stories_event.dart
|
abstract class UserStoriesEvent {}
class GetStories extends UserStoriesEvent {}
class GetCategoryStories extends UserStoriesEvent {
final int? categoryId;
final int userId;
GetCategoryStories({
this.categoryId,
required this.userId,
});
}
class GetCategories extends UserStoriesEvent {
final int userId;
GetCategories({
required this.userId,
});
}
class SetAsRead extends UserStoriesEvent {
final int storyId;
SetAsRead({
required this.storyId,
});
}
class SetUserId extends UserStoriesEvent {
final int id;
SetUserId({
required this.id,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/profile/profile_state.dart
|
part of 'profile_bloc.dart';
enum ProfileStatus {
loading,
success,
fail,
}
class ProfileState extends Equatable {
final ProfileStatus? profileStatus;
final ProfileStatus? profileStatsStatus;
final User? profile;
final ProfileStats? profileStats;
@override
List<Object?> get props => [
profileStatus,
profileStats,
];
const ProfileState({
this.profileStatus,
this.profileStatsStatus,
this.profile,
this.profileStats,
});
ProfileState copyWith({
ProfileStatus? profileStatus,
ProfileStatus? profileStatsStatus,
User? profile,
ProfileStats? profileStats,
}) {
return ProfileState(
profileStatus: profileStatus ?? this.profileStatus,
profileStatsStatus: profileStatsStatus ?? this.profileStatsStatus,
profile: profile ?? this.profile,
profileStats: profileStats ?? this.profileStats,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/profile/profile_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/domain/models/ui/profile_stats.dart';
import '../../../../domain/models/common/domain_result.dart';
import '../../../../domain/models/ui/profile.dart';
import '../../../../domain/repositories/profile_repository.dart';
part 'profile_event.dart';
part 'profile_state.dart';
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
final ProfileRepository _repository;
ProfileBloc(this._repository) : super(const ProfileState()) {
on<GetProfile>(_getProfile);
on<GetProfileStats>(_getProfileStats);
on<LogOut>(_logout);
}
Future<void> _logout(LogOut event, Emitter emitter) async {
_repository.logout();
}
Future<void> _getProfile(GetProfile event, Emitter emitter) {
return emitter.forEach(
_repository.getProfile(),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(profileStatus: ProfileStatus.loading);
}
if (data is DomainSuccess<User>) {
return state.copyWith(
profileStatus: ProfileStatus.success, profile: data.data);
}
if (data is DomainFail) {
return state.copyWith(profileStatus: ProfileStatus.fail);
}
return state;
},
);
}
Future<void> _getProfileStats(GetProfileStats event, Emitter emitter) {
return emitter.forEach(
_repository.getStats(),
onData: (data) {
printMessage('get stats : $data');
if (data is DomainLoading) {
return state.copyWith(profileStatsStatus: ProfileStatus.loading);
}
if (data is DomainSuccess<ProfileStats>) {
return state.copyWith(
profileStatsStatus: ProfileStatus.success,
profileStats: data.data);
}
if (data is DomainFail) {
return state.copyWith(profileStatsStatus: ProfileStatus.fail);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/profile/bloc
|
mirrored_repositories/stories-app/lib/ui/profile/bloc/profile/profile_event.dart
|
part of 'profile_bloc.dart';
abstract class ProfileEvent {}
class GetProfile extends ProfileEvent {}
class GetProfileStats extends ProfileEvent {}
class LogOut extends ProfileEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/view_story/view_story_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/story_quotes/story_quotes_screen.dart';
import 'package:jokes_app/ui/view_story/view/view_story_bloc.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import '../../common/widgets/animated_text/lib/animated_text_kit.dart';
import '../../domain/models/ui/story.dart';
import '../../generated/locale_keys.g.dart';
import '../common/dialog/about.dart';
class ViewStoryScreen extends StatefulWidget {
final Story story;
final Function() onReadFinish;
final Function() onUnpublish;
@override
State<ViewStoryScreen> createState() => _ViewStoryScreenState();
const ViewStoryScreen({
super.key,
required this.story,
required this.onUnpublish,
required this.onReadFinish,
});
}
class _ViewStoryScreenState extends State<ViewStoryScreen> {
bool _titleAnimFinish = false;
bool _dateAnimFinish = false;
bool _contentAnimFinish = false;
@override
Widget build(BuildContext context) {
return BlocProvider<ViewStoryBloc>(
create: (_) => ViewStoryBloc(
injector.get(),
),
child: BlocBuilder<ViewStoryBloc, ViewStoryState>(
builder: (context, state) {
final bloc = context.read<ViewStoryBloc>();
return MultiBlocListener(
listeners: [
BlocListener<ViewStoryBloc, ViewStoryState>(
listener: (context, state) {
if (state.quoteCreateStatus == ViewStoryStatus.success) {
context.showSnackBar(Strings.published);
}
if (state.quoteCreateStatus == ViewStoryStatus.fail) {
context.showSnackBar(Strings.somethingWentWrong);
}
},
listenWhen: (prev, curr) =>
prev.quoteCreateStatus != curr.quoteCreateStatus,
),
BlocListener<ViewStoryBloc, ViewStoryState>(
listener: (context, state) {
if (state.sendReportStatus == ViewStoryStatus.success) {
showCupertinoModalBottomSheet(
context: context,
builder: (context) {
return About(
text: Strings.reportSent,
);
},
);
}
if (state.sendReportStatus == ViewStoryStatus.fail) {
context.showSnackBar(Strings.somethingWentWrong);
}
},
listenWhen: (prev, curr) =>
prev.sendReportStatus != curr.sendReportStatus,
),
],
child: Scaffold(
backgroundColor: AppColors.primaryColorBlack,
extendBodyBehindAppBar: true,
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
context.navigateTo(StoryQuotesScreen(
title: widget.story.title, storyId: widget.story.id));
},
icon: Icon(
Icons.format_quote,
color: AppColors.gold,
),
),
if (!widget.story.canModify && _contentAnimFinish)
IconButton(
onPressed: () {
bloc.add(SendReport(storyId: widget.story.id));
},
icon: Icon(
Icons.mood_bad,
color: AppColors.gold,
),
),
if (widget.story.canModify &&
state.unpublishStatus != ViewStoryStatus.success)
IconButton(
onPressed: () {
bloc.add(ToggleVisibility(
storyId: widget.story.id,
enabled: !widget.story.isPublished));
widget.onUnpublish.call();
},
icon: Icon(
widget.story.isPublished
? Icons.unpublished_outlined
: Icons.public,
color: widget.story.isPublished
? AppColors.red
: AppColors.darkSpringGreen,
),
)
],
backgroundColor: Colors.transparent,
title: Text(widget.story.authorName),
),
body: GestureDetector(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(
top: 100, left: 24, right: 24),
child: AnimatedTextKit(
isRepeatingAnimation: false,
onFinished: () {
setState(() {
_titleAnimFinish = true;
});
},
animatedTexts: [
TypewriterAnimatedText(
speed: const Duration(milliseconds: 30),
widget.story.title,
textStyle: primaryTextStyle(
fontSize: 16, color: AppColors.grey),
),
],
onTap: () {
//
},
),
),
if (_titleAnimFinish)
Container(
padding: const EdgeInsets.only(
top: 4, left: 24, right: 24),
child: AnimatedTextKit(
isRepeatingAnimation: false,
onFinished: () {
setState(
() {
_dateAnimFinish = true;
},
);
},
animatedTexts: [
TypewriterAnimatedText(
speed: const Duration(milliseconds: 30),
widget.story.timeCreate,
textStyle: primaryTextStyle(
fontSize: 14, color: AppColors.grey),
),
],
onTap: () {
//
},
),
),
const Padding(
padding: EdgeInsets.all(18),
),
if (_dateAnimFinish)
Container(
padding: const EdgeInsets.only(
top: 24, left: 24, right: 24, bottom: 42),
child: AnimatedTextKit(
totalRepeatCount: 1,
onFinished: () {
widget.onReadFinish.call();
setState(() {
_contentAnimFinish = true;
});
},
animatedTexts: [
TypewriterAnimatedText(
speed: const Duration(milliseconds: 30),
widget.story.body,
textStyle: primaryTextStyle(fontSize: 16),
selectionActions: (selectedText) {
return [
InkWell(
onTap: () {
bloc.add(CreateQuote(
storyId: widget.story.id,
body: selectedText));
FocusManager.instance.primaryFocus
?.unfocus();
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
color: AppColors.primaryColor,
padding: const EdgeInsets.all(12),
child: Text(
Strings.addToQuotes,
style: primaryTextStyle(
color: AppColors
.darkSpringGreen),
),
),
],
),
),
];
},
),
],
onTap: () {
//
},
),
),
],
),
),
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/view_story
|
mirrored_repositories/stories-app/lib/ui/view_story/view/view_story_state.dart
|
part of 'view_story_bloc.dart';
enum ViewStoryStatus {
success,
fail,
loading,
}
class ViewStoryState extends Equatable {
final ViewStoryStatus? unpublishStatus;
final ViewStoryStatus? quoteCreateStatus;
final ViewStoryStatus? sendReportStatus;
const ViewStoryState({
this.unpublishStatus,
this.quoteCreateStatus,
this.sendReportStatus,
});
ViewStoryState copyWith({
ViewStoryStatus? unpublishStatus,
ViewStoryStatus? quoteCreateStatus,
ViewStoryStatus? sendReportStatus,
}) {
return ViewStoryState(
unpublishStatus: unpublishStatus ?? this.unpublishStatus,
quoteCreateStatus: quoteCreateStatus ?? this.quoteCreateStatus,
sendReportStatus: sendReportStatus ?? this.sendReportStatus,
);
}
@override
List<Object?> get props => [
unpublishStatus,
quoteCreateStatus,
sendReportStatus,
];
}
| 0
|
mirrored_repositories/stories-app/lib/ui/view_story
|
mirrored_repositories/stories-app/lib/ui/view_story/view/view_story_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:meta/meta.dart';
import '../../../domain/repositories/view_story_repository.dart';
part 'view_story_event.dart';
part 'view_story_state.dart';
class ViewStoryBloc extends Bloc<ViewStoryEvent, ViewStoryState> {
final ViewStoryRepository _repository;
ViewStoryBloc(
this._repository,
) : super(const ViewStoryState()) {
on<ToggleVisibility>(_unpublish);
on<CreateQuote>(_createQuote);
on<SendReport>(_sendReport);
}
Future<void> _sendReport(SendReport event, Emitter emitter) async {
emitter(state.copyWith(sendReportStatus: ViewStoryStatus.loading));
final res = await _repository.sendReport(event.storyId);
if (res) {
emitter(state.copyWith(sendReportStatus: ViewStoryStatus.success));
} else {
emitter(state.copyWith(sendReportStatus: ViewStoryStatus.fail));
}
}
Future<void> _unpublish(ToggleVisibility event, Emitter emitter) async {
return emitter.forEach(
_repository.unpublish(event.storyId, event.enabled),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(unpublishStatus: ViewStoryStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(unpublishStatus: ViewStoryStatus.fail);
}
if (data is DomainSuccess) {
return state.copyWith(unpublishStatus: ViewStoryStatus.success);
}
return state;
},
);
}
Future<void> _createQuote(CreateQuote event, Emitter emitter) async {
return emitter.forEach(
_repository.createQuote(event.storyId, event.body),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(quoteCreateStatus: ViewStoryStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(quoteCreateStatus: ViewStoryStatus.fail);
}
if (data is DomainSuccess) {
return state.copyWith(quoteCreateStatus: ViewStoryStatus.success);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/view_story
|
mirrored_repositories/stories-app/lib/ui/view_story/view/view_story_event.dart
|
part of 'view_story_bloc.dart';
@immutable
abstract class ViewStoryEvent {}
class ToggleVisibility extends ViewStoryEvent {
final int storyId;
final bool enabled;
ToggleVisibility({
required this.storyId,
required this.enabled,
});
}
class SendReport extends ViewStoryEvent {
final int storyId;
SendReport({
required this.storyId,
});
}
class CreateQuote extends ViewStoryEvent {
final int storyId;
final String body;
CreateQuote({
required this.storyId,
required this.body,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/common
|
mirrored_repositories/stories-app/lib/ui/common/dialog/language_item.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:modified_localization/easy_localization.dart';
import '../../../common/language/language.dart';
import '../../../common/resource/colors.dart';
class LanguageItem extends StatelessWidget {
final Function _onTap;
final LanguageInfo _languageInfo;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
border: Border.all(color: AppColors.whiteAlpha52),
color: AppColors.primaryColor,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () {
_onTap.call();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const Padding(
padding: EdgeInsets.all(4),
),
Text(
_languageInfo.title,
style: primaryTextStyle(fontWeight: FontWeight.w500),
),
],
),
...[
if (_languageInfo.locale.languageCode ==
context.locale.languageCode)
Icon(
Icons.check_circle,
color: AppColors.darkSpringGreen,
)
else
Icon(
Icons.circle_outlined,
color: AppColors.whiteAlpha52,
),
],
],
),
),
],
),
);
}
const LanguageItem({
super.key,
required Function onTap,
required LanguageInfo languageInfo,
}) : _onTap = onTap,
_languageInfo = languageInfo;
}
| 0
|
mirrored_repositories/stories-app/lib/ui/common
|
mirrored_repositories/stories-app/lib/ui/common/dialog/select_language_dialog.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:modified_localization/easy_localization.dart';
import '../../../common/language/language.dart';
import '../../../generated/locale_keys.g.dart';
import 'language_item.dart';
class SelectLanguage extends StatelessWidget {
final Function(LanguageInfo languageInfo) onSelect;
@override
Widget build(BuildContext context) {
return Material(
color: AppColors.primaryColor,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
child: Padding(
padding: const EdgeInsets.only(top: 8, left: 16, right: 16, bottom: 18),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
Strings.selectLanguage,
style:
primaryTextStyle(fontWeight: FontWeight.bold, fontSize: 24),
),
const Padding(
padding: EdgeInsets.all(2),
),
Text(
Strings.selectLanguage,
style: primaryTextStyle(),
),
const Padding(
padding: EdgeInsets.all(6),
),
SizedBox(
height: 252,
child: ListView.separated(
physics: const NeverScrollableScrollPhysics(),
itemCount: Language.supportedLanguagesInfo.length,
itemBuilder: (e, i) {
return LanguageItem(
onTap: () async {
context
.setLocale(Language.supportedLanguagesInfo[i].locale);
onSelect.call(Language.supportedLanguagesInfo[i]);
context.goBack();
},
languageInfo: Language.supportedLanguagesInfo[i],
);
},
separatorBuilder: (BuildContext context, int index) {
return const Divider();
},
),
),
],
),
),
);
}
const SelectLanguage({
super.key,
required this.onSelect,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/common
|
mirrored_repositories/stories-app/lib/ui/common/dialog/about.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
class About extends StatelessWidget {
final String text;
@override
Widget build(BuildContext context) {
return Material(
color: AppColors.primaryColor,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
child: Container(
padding: const EdgeInsets.all(24),
child: Text(
text,
style: primaryTextStyle(),
),
),
);
}
const About({
required this.text,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/common
|
mirrored_repositories/stories-app/lib/ui/common/dialog/logout.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/button.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
class LogOutContent extends StatelessWidget {
final Function() onPositive;
@override
Widget build(BuildContext context) {
return Material(
elevation: 0,
color: AppColors.primaryColor,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.all(24),
child: Text(
Strings.doYouWantLogout,
style: primaryTextStyle(),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: Button(
height: 42,
width: context.width,
onTap: () {
context.goBack();
},
text: Strings.no,
margin: const EdgeInsets.all(24),
),
),
Flexible(
child: Button(
height: 42,
width: context.width,
onTap: () {
onPositive.call();
},
text: Strings.yes,
margin: const EdgeInsets.all(24),
),
),
],
)
],
),
);
}
const LogOutContent({
super.key,
required this.onPositive,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth
|
mirrored_repositories/stories-app/lib/ui/auth/login/login_screen.dart
|
import 'package:animate_gradient/animate_gradient.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/assets.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/common/utils/ui.dart';
import 'package:jokes_app/common/widgets/button.dart';
import 'package:jokes_app/common/widgets/input_widget.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/auth/login/bloc/login_bloc.dart';
import 'package:jokes_app/ui/auth/register/register_screen.dart';
import 'package:jokes_app/ui/home/home_screen.dart';
import 'package:lottie/lottie.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen>
with TickerProviderStateMixin {
late AnimationController _animationController;
@override
void initState() {
_animationController = AnimationController(vsync: this);
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => LoginBloc(
injector.get(),
),
child: BlocBuilder<LoginBloc, LoginState>(
builder: (context, state) {
final bloc = context.read<LoginBloc>();
return MultiBlocListener(
listeners: [
BlocListener<LoginBloc, LoginState>(
listener: (context, state) {
if (state.loginStatus == LoginStatus.success) {
context.navigateTo(const HomeScreen(), removeStack: true);
}
if (state.loginStatus == LoginStatus.fail) {
context.showSnackBar(Strings.somethingWentWrong,
status: MessageStatus.fail);
}
},
),
],
child: Scaffold(
body: AnimateGradient(
duration: Duration(milliseconds: 500),
controller: _animationController,
primaryColors: [
AppColors.darkGreen,
AppColors.primaryColor,
AppColors.primaryColor,
],
secondaryColors: [
AppColors.primaryColor,
AppColors.primaryColorBlack,
AppColors.primaryColorBlack,
],
child: Container(
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Spacer(),
SizedBox(
height: 100,
child: Lottie.asset(
Assets.writeJson,
frameRate: FrameRate.max,
width: 152,
height: 152,
),
),
const Spacer(),
Input(
controller: bloc.usernameController,
hint: Strings.username,
margin: const EdgeInsets.only(left: 24, right: 24)),
Input(
controller: bloc.passwordController,
hint: Strings.password,
margin: const EdgeInsets.all(24)),
InkWell(
onTap: () {
context.navigateTo(const RegisterScreen());
},
child: Container(
margin: const EdgeInsets.only(right: 32),
alignment: Alignment.centerRight,
child: Text(
Strings.dontHaveAccountRegister,
style: primaryTextStyle(
color: AppColors.darkSpringGreen,
fontWeight: FontWeight.bold),
),
),
),
const Spacer(),
const Spacer(),
Button(
enabled: state.loginStatus != LoginStatus.loading,
margin: const EdgeInsets.all(24),
onTap: () {
bloc.add(Login());
unFocus();
},
text: Strings.login,
height: 56,
),
],
),
),
),
),
);
},
),
);
}
@override
void dispose() {
super.dispose();
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/login
|
mirrored_repositories/stories-app/lib/ui/auth/login/bloc/login_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import '../../../../domain/repositories/auth_repository.dart';
part 'login_event.dart';
part 'login_state.dart';
class LoginBloc extends Bloc<LoginEvent, LoginState> {
final AuthRepository _repository;
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
LoginBloc(
this._repository,
) : super(const LoginState()) {
on<Login>(_login);
}
Future<void> _login(Login event, Emitter emitter) {
return emitter.forEach(
_repository.login(usernameController.text, passwordController.text),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(loginStatus: LoginStatus.loading);
}
if (data is DomainSuccess) {
return state.copyWith(loginStatus: LoginStatus.success);
}
if (data is DomainFail) {
return state.copyWith(loginStatus: LoginStatus.fail);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/login
|
mirrored_repositories/stories-app/lib/ui/auth/login/bloc/login_state.dart
|
part of 'login_bloc.dart';
enum LoginStatus {
loading,
success,
fail,
}
class LoginState extends Equatable {
final LoginStatus? loginStatus;
const LoginState({
this.loginStatus,
});
@override
List<Object?> get props => [
loginStatus,
];
LoginState copyWith({
LoginStatus? loginStatus,
}) {
return LoginState(
loginStatus: loginStatus ?? this.loginStatus,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/login
|
mirrored_repositories/stories-app/lib/ui/auth/login/bloc/login_event.dart
|
part of 'login_bloc.dart';
@immutable
abstract class LoginEvent {}
class Login extends LoginEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth
|
mirrored_repositories/stories-app/lib/ui/auth/register/register_screen.dart
|
import 'package:animate_gradient/animate_gradient.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/assets.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/common/utils/ui.dart';
import 'package:jokes_app/common/widgets/button.dart';
import 'package:jokes_app/common/widgets/input_widget.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/auth/register/bloc/register_bloc.dart';
import 'package:lottie/lottie.dart';
import '../../../common/resource/colors.dart';
import '../../home/home_screen.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({super.key});
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen>
with TickerProviderStateMixin {
late AnimationController _animationController;
@override
void initState() {
_animationController = AnimationController(vsync: this);
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => RegisterBloc(
injector.get(),
),
child: BlocBuilder<RegisterBloc, RegisterState>(
builder: (context, state) {
final bloc = context.read<RegisterBloc>();
return MultiBlocListener(
listeners: [
BlocListener<RegisterBloc, RegisterState>(
listener: (context, state) {
if (state.registerStatus == RegisterStatus.success) {
context.navigateTo(const HomeScreen(), removeStack: true);
}
if (state.registerStatus == RegisterStatus.fail) {
context.showSnackBar(Strings.somethingWentWrong,
status: MessageStatus.fail);
}
},
),
],
child: Material(
child: AnimateGradient(
controller: _animationController,
primaryColors: [
AppColors.darkGreen,
AppColors.primaryColor,
AppColors.primaryColor,
],
secondaryColors: [
AppColors.primaryColor,
AppColors.primaryColorBlack,
AppColors.primaryColorBlack,
],
child: Container(
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Spacer(),
SizedBox(
height: 100,
child: Lottie.asset(
Assets.writeJson,
frameRate: FrameRate.max,
width: 152,
height: 152,
),
),
const Spacer(),
Input(
controller: bloc.usernameController,
hint: Strings.username,
margin: const EdgeInsets.only(left: 24, right: 24)),
Input(
controller: bloc.passwordController,
hint: Strings.password,
margin: const EdgeInsets.all(24)),
const Spacer(),
const Spacer(),
Button(
enabled: state.registerStatus != RegisterStatus.loading,
margin: const EdgeInsets.all(24),
onTap: () {
bloc.add(Register());
unFocus();
},
text: Strings.register,
height: 56,
),
],
),
),
),
),
);
},
),
);
}
@override
void dispose() {
super.dispose();
_animationController.dispose();
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/register
|
mirrored_repositories/stories-app/lib/ui/auth/register/bloc/register_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:meta/meta.dart';
import '../../../../domain/repositories/auth_repository.dart';
part 'register_event.dart';
part 'register_state.dart';
class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
final AuthRepository _repository;
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
RegisterBloc(
this._repository,
) : super(const RegisterState()) {
on<Register>(_register);
}
Future<void> _register(Register event, Emitter emitter) {
return emitter.forEach(
_repository.register(usernameController.text, passwordController.text),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(registerStatus: RegisterStatus.loading);
}
if (data is DomainSuccess) {
return state.copyWith(registerStatus: RegisterStatus.success);
}
if (data is DomainFail) {
return state.copyWith(registerStatus: RegisterStatus.fail);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/register
|
mirrored_repositories/stories-app/lib/ui/auth/register/bloc/register_state.dart
|
part of 'register_bloc.dart';
enum RegisterStatus {
loading,
success,
fail,
}
@immutable
class RegisterState extends Equatable {
final RegisterStatus? registerStatus;
const RegisterState({
this.registerStatus,
});
@override
List<Object?> get props => [
registerStatus,
];
RegisterState copyWith({
RegisterStatus? registerStatus,
}) {
return RegisterState(
registerStatus: registerStatus ?? this.registerStatus,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/auth/register
|
mirrored_repositories/stories-app/lib/ui/auth/register/bloc/register_event.dart
|
part of 'register_bloc.dart';
abstract class RegisterEvent {}
class Register extends RegisterEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/home/home_screen.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/ui.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/global/global_screen.dart';
import 'package:jokes_app/ui/profile/notifications/notifications_screen.dart';
import 'package:quick_actions/quick_actions.dart';
import '../../common/resource/colors.dart';
import '../profile/profile_screen.dart';
import '../publish/publish_screen.dart';
import '../stories/stories_screen.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0;
@override
void initState() {
_initQuickActions();
super.initState();
}
void _initQuickActions() {
const QuickActions quickActions = QuickActions();
quickActions.initialize((shortcutType) {
if (shortcutType == 'profile') {
setState(() {
_selectedIndex = 3;
});
}
if (shortcutType == 'publish') {
setState(() {
_selectedIndex = 2;
});
}
if (shortcutType == 'notifications') {
context.navigateTo(const NotificationsScreen());
}
});
quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'profile', localizedTitle: Strings.profile, icon: 'profile'),
ShortcutItem(
type: 'publish', localizedTitle: Strings.publish, icon: 'add_new_icon'),
ShortcutItem(
type: 'notifications',
localizedTitle: Strings.notifications,
icon: 'notification')
]);
}
final _screens = [
const StoriesScreen(),
const GlobalScreen(),
const PublishScreen(),
const ProfileScreen(),
];
@override
Widget build(BuildContext context) {
setNavColor();
final screenTitles = [
Strings.stories,
Strings.global,
Strings.publish,
Strings.profile,
];
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.black,
currentIndex: _selectedIndex,
onTap: (index) {
setState(
() {
_selectedIndex = index;
},
);
},
selectedItemColor: AppColors.darkSpringGreen,
unselectedItemColor: Colors.white.withAlpha(72),
unselectedLabelStyle: const TextStyle(color: Colors.black12),
items: [
BottomNavigationBarItem(
label: Strings.stories,
icon: const Icon(Icons.pending),
),
BottomNavigationBarItem(
label: Strings.global,
icon: const Icon(Icons.public),
),
BottomNavigationBarItem(
label: Strings.publish,
icon: const Icon(Icons.add),
),
BottomNavigationBarItem(
label: Strings.profile,
icon: const Icon(Icons.person),
),
],
),
appBar: AppBar(
elevation: 0,
title: Text(
screenTitles[_selectedIndex],
style: primaryTextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
backgroundColor: AppColors.primaryColorBlack,
),
body: _screens[_selectedIndex],
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/story_quotes/generate_quote_image_dialog.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import '../../common/utils/file.dart';
void showGenerateQuoteDialog(BuildContext context, String text) {
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) {
return Material(
color: Colors.transparent,
child: _DialogContent(
text: text,
),
);
},
);
}
class _ImageContent extends StatelessWidget {
final String text;
final Color color;
final ScreenshotController screenshotController;
@override
Widget build(BuildContext context) {
return Container(
height: 252,
margin: const EdgeInsets.all(16),
child: Screenshot(
controller: screenshotController,
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(16),
),
alignment: Alignment.center,
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Text(
maxLines: 8,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
text,
style: primaryTextStyle(),
),
),
Align(
alignment: Alignment.bottomRight,
child: Text(
maxLines: 10,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
"Stories app",
style: primaryTextStyle(
color: AppColors.whiteAlpha52, fontSize: 12),
),
),
],
),
),
),
);
}
const _ImageContent({
required this.text,
required this.color,
required this.screenshotController,
});
}
class _DialogContent extends StatefulWidget {
final String text;
@override
State<_DialogContent> createState() => _DialogContentState();
const _DialogContent({
required this.text,
});
}
class _DialogContentState extends State<_DialogContent> {
Color _backgroundColor = Colors.black;
ScreenshotController screenshotController = ScreenshotController();
int _selectedIndex = 0;
final List<Color> _colors = [];
@override
void initState() {
_colors.add(Colors.black);
_colors.add(Colors.white);
for (int i = 0; i < 50; i++) {
_colors.add(Color.fromARGB(Random().nextInt(255), Random().nextInt(255),
Random().nextInt(255), Random().nextInt(255)));
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
height: 400,
alignment: Alignment.center,
decoration: BoxDecoration(
color: AppColors.primaryColor,
borderRadius: BorderRadius.circular(24),
),
margin: const EdgeInsets.all(12),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ScaleTap(
onPressed: () {
setState(() {
_selectedIndex = Random().nextInt(50);
_backgroundColor = _colors[_selectedIndex];
});
},
child: _ImageContent(
color: _backgroundColor,
text: widget.text,
screenshotController: screenshotController,
),
),
_ImageBackgroundPicker(
onPick: (color, index) {
setState(
() {
_backgroundColor = color;
_selectedIndex = index;
},
);
},
selectedIndex: _selectedIndex,
colors: _colors,
),
Row(
children: [
const Spacer(),
Container(
margin: const EdgeInsets.only(top: 12, right: 16, bottom: 16),
child: FloatingActionButton(
splashColor: AppColors.darkSpringGreen,
backgroundColor: AppColors.darkGreen,
child: const Icon(Icons.send),
onPressed: () async {
final path = await screenshotController.captureAndSave(
(await FileUtils.generateFilePath("jpeg")));
if (path != null) {
Share.shareXFiles([XFile(path)]);
}
},
),
),
],
)
],
),
);
}
}
class _ImageBackgroundPicker extends StatefulWidget {
final Function(Color color, int index) onPick;
final int selectedIndex;
final List<Color> colors;
@override
State<_ImageBackgroundPicker> createState() => _ImageBackgroundPickerState();
const _ImageBackgroundPicker({
required this.onPick,
required this.selectedIndex,
required this.colors,
});
}
class _ImageBackgroundPickerState extends State<_ImageBackgroundPicker>
with TickerProviderStateMixin {
late TabController tabController;
@override
void initState() {
tabController = TabController(length: 50, vsync: this);
super.initState();
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: 32,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.only(left: 16, right: 16),
scrollDirection: Axis.horizontal,
itemCount: widget.colors.length,
itemBuilder: (e, i) {
final item = widget.colors[i];
return ScaleTap(
onPressed: () {
widget.onPick.call(item, i);
},
child: Container(
margin: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: item,
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(2),
height: 24,
width: 24,
child: Container(
width: 16,
decoration: BoxDecoration(
color: item,
border: widget.selectedIndex == i
? Border.all(color: Colors.black, width: 2)
: null,
borderRadius: BorderRadius.circular(12),
),
height: 16,
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/story_quotes/story_quotes_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/widgets/loading.dart';
import 'package:jokes_app/common/widgets/not_found.dart';
import 'package:jokes_app/common/widgets/story_quote_item.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/profile/user_stories_screen.dart';
import 'package:jokes_app/ui/story_quotes/bloc/story_quotes_bloc.dart';
import 'package:jokes_app/ui/story_quotes/generate_quote_image_dialog.dart';
import '../../common/resource/colors.dart';
import '../../di/app_di.dart';
class StoryQuotesScreen extends StatelessWidget {
final String title;
final int storyId;
@override
Widget build(BuildContext context) {
return BlocProvider<StoryQuotesBloc>(
create: (_) => StoryQuotesBloc(
injector.get(),
)..add(
GetQuotes(storyId: storyId),
),
child: BlocBuilder<StoryQuotesBloc, StoryQuotesState>(
builder: (context, state) {
final bloc = context.read<StoryQuotesBloc>();
return Scaffold(
backgroundColor: AppColors.primaryColorBlack,
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
title: Text(
"${Strings.quotes} $title",
style:
primaryTextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
body: state.quotes.isEmpty
? state.quotesStatus == StoryQuotesStatus.success
? const NotFound()
: const Loading()
: ListView.separated(
itemCount: state.quotes.length,
itemBuilder: (e, i) {
final item = state.quotes[i];
return StoryQuoteItem(
item: item,
onTap: () {
showGenerateQuoteDialog(context, item.body);
},
onTapOwner: () {
context.navigateTo(UserStoriesScreen(
userId: item.userId, username: item.username));
},
);
},
separatorBuilder: (BuildContext context, int index) {
return Divider(
color: AppColors.whiteAlpha52,
);
},
),
);
},
),
);
}
const StoryQuotesScreen({
super.key,
required this.title,
required this.storyId,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/story_quotes
|
mirrored_repositories/stories-app/lib/ui/story_quotes/bloc/story_quotes_event.dart
|
part of 'story_quotes_bloc.dart';
@immutable
abstract class StoryQuotesEvent {}
class GetQuotes extends StoryQuotesEvent {
final int storyId;
GetQuotes({
required this.storyId,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/story_quotes
|
mirrored_repositories/stories-app/lib/ui/story_quotes/bloc/story_quotes_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:jokes_app/domain/models/ui/story.dart';
import 'package:meta/meta.dart';
import '../../../domain/models/ui/story_quote.dart';
import '../../../domain/repositories/story_quotes_repository.dart';
part 'story_quotes_event.dart';
part 'story_quotes_state.dart';
class StoryQuotesBloc extends Bloc<StoryQuotesEvent, StoryQuotesState> {
final StoryQuotesRepository _repository;
StoryQuotesBloc(
this._repository,
) : super(const StoryQuotesState()) {
on<GetQuotes>(_getQuotes);
}
Future<void> _getQuotes(GetQuotes event, Emitter emitter) async {
return emitter.forEach(
_repository.getQuotes(event.storyId),
onData: (data) {
printMessage("Status : ${data}");
if (data is DomainLoading) {
return state.copyWith(quotesStatus: StoryQuotesStatus.loading);
}
if (data is DomainSuccess<List<StoryQuote>>) {
return state.copyWith(
quotesStatus: StoryQuotesStatus.success, quotes: data.data);
}
if (data is DomainFail) {
return state.copyWith(quotesStatus: StoryQuotesStatus.error);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/story_quotes
|
mirrored_repositories/stories-app/lib/ui/story_quotes/bloc/story_quotes_state.dart
|
part of 'story_quotes_bloc.dart';
enum StoryQuotesStatus {
loading,
success,
error,
}
class StoryQuotesState extends Equatable {
final StoryQuotesStatus? quotesStatus;
final List<StoryQuote> quotes;
@override
List<Object?> get props => [
quotesStatus,
quotes,
];
const StoryQuotesState({
this.quotesStatus,
this.quotes = const [],
});
StoryQuotesState copyWith({
StoryQuotesStatus? quotesStatus,
List<StoryQuote>? quotes,
}) {
return StoryQuotesState(
quotesStatus: quotesStatus ?? this.quotesStatus,
quotes: quotes ?? this.quotes,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/publish/publish_screen.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/button.dart';
import 'package:jokes_app/common/widgets/input_widget.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/publish/bloc/publish_bloc.dart';
import '../../common/resource/decorations.dart';
import '../../generated/locale_keys.g.dart';
import '../stories/story_category_item.dart';
class PublishScreen extends StatefulWidget {
const PublishScreen({super.key});
@override
State<PublishScreen> createState() => _PublishScreenState();
}
class _PublishScreenState extends State<PublishScreen> {
bool publishButtonEnabled = false;
Timer? _debounce;
_onInputValueChanged(PublishBloc bloc) {
if (_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 100), () {
setState(() {
publishButtonEnabled = bloc.bodyController.text.trim().isNotEmpty &&
bloc.titleController.text.trim().isNotEmpty &&
bloc.selectedCategoryIndex != -1;
});
});
}
@override
void dispose() {
_debounce?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider<PublishBloc>(
create: (_) => PublishBloc(
injector.get(),
)..add(
GetCategories(),
),
child: BlocBuilder<PublishBloc, PublishState>(
builder: (context, state) {
final bloc = context.read<PublishBloc>();
return MultiBlocListener(
listeners: [
BlocListener<PublishBloc, PublishState>(
listener: (context, state) {
if (state.publishStatus == PublishStatus.fail) {
context.showSnackBar(Strings.somethingWentWrong);
}
if (state.publishStatus == PublishStatus.success) {
context.showSnackBar(Strings.published);
}
},
listenWhen: (prev, curr) =>
prev.publishStatus != curr.publishStatus,
)
],
child: Scaffold(
body: Container(
height: context.height,
decoration: const DefaultBackgroundDecoration(),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
controller: ScrollController(),
child: Column(
children: [
Input(
onChange: (str) {
_onInputValueChanged(bloc);
},
maxLength: 100,
controller: bloc.titleController,
hint: Strings.title,
margin: const EdgeInsets.only(
left: 24, right: 24, top: 24, bottom: 0),
multiLine: false,
),
Row(
children: [
const Spacer(),
Container(
margin: const EdgeInsets.only(right: 32, top: 16),
child: Text(
"${bloc.titleController.text.length.toString()}/100",
style: primaryTextStyle(),
),
),
],
),
SizedBox(
height: 72,
child: ListView.builder(
padding: const EdgeInsets.only(
left: 12, right: 12, top: 12, bottom: 12),
itemCount: state.categories.length,
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemBuilder: (e, i) {
final item = (state.categories)[i];
return StoryCategoryItem(
value: item,
selected: bloc.selectedCategoryIndex == i,
onTap: () {
setState(
() {
_onInputValueChanged(bloc);
bloc.selectedCategoryIndex = i;
},
);
},
);
},
),
),
Input(
maxLength: 1000,
controller: bloc.bodyController,
hint: Strings.body,
onChange: (text) {
_onInputValueChanged(bloc);
},
margin: const EdgeInsets.all(24),
multiLine: true,
),
Row(
children: [
const Spacer(),
Container(
margin: const EdgeInsets.only(right: 32),
child: Text(
"${bloc.bodyController.text.length.toString()}/1000",
style: primaryTextStyle(),
),
),
],
),
Button(
animate: state.publishStatus == PublishStatus.loading,
enabled: publishButtonEnabled,
height: 52,
onTap: () {
bloc.add(PublishStory(
categoryId: state
.categories[bloc.selectedCategoryIndex].id));
},
text: Strings.publish,
margin: const EdgeInsets.all(24),
),
],
),
),
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/publish
|
mirrored_repositories/stories-app/lib/ui/publish/bloc/publish_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:meta/meta.dart';
import '../../../domain/models/common/domain_result.dart';
import '../../../domain/models/ui/category.dart';
import '../../../domain/repositories/publish_repository.dart';
part 'publish_event.dart';
part 'publish_state.dart';
class PublishBloc extends Bloc<PublishEvent, PublishState> {
final PublishRepository _repository;
final TextEditingController bodyController = TextEditingController();
final TextEditingController titleController = TextEditingController();
int selectedCategoryIndex = -1;
PublishBloc(
this._repository,
) : super(const PublishState()) {
on<PublishStory>(_publishStory);
on<GetCategories>(_getCategories);
}
Future<void> _publishStory(PublishStory event, Emitter emitter) async {
return emitter.forEach(
_repository.publishStory(
bodyController.text, titleController.text, event.categoryId),
onData: (data) {
printMessage(data);
if (data is DomainLoading) {
bodyController.clear();
titleController.clear();
selectedCategoryIndex = -1;
return state.copyWith(publishStatus: PublishStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(publishStatus: PublishStatus.fail);
}
if (data is DomainSuccess) {
return state.copyWith(publishStatus: PublishStatus.success);
}
return state;
},
);
}
Future<void> _getCategories(GetCategories event, Emitter emitter) async {
return emitter.forEach(
_repository.getCategories(),
onData: (data) {
printMessage(data);
if (data is DomainLoading) {
bodyController.clear();
titleController.clear();
return state.copyWith();
}
if (data is DomainFail) {
return state.copyWith();
}
if (data is DomainSuccess) {
return state.copyWith(categories: data.data);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/publish
|
mirrored_repositories/stories-app/lib/ui/publish/bloc/publish_state.dart
|
part of 'publish_bloc.dart';
enum PublishStatus {
loading,
success,
fail,
}
@immutable
class PublishState extends Equatable {
final PublishStatus? publishStatus;
final List<Category> categories;
@override
List<Object?> get props => [
publishStatus,
categories,
];
const PublishState({
this.publishStatus,
this.categories = const [],
});
PublishState copyWith({
PublishStatus? publishStatus,
List<Category>? categories,
}) {
return PublishState(
publishStatus: publishStatus ?? this.publishStatus,
categories: categories ?? this.categories,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/publish
|
mirrored_repositories/stories-app/lib/ui/publish/bloc/publish_event.dart
|
part of 'publish_bloc.dart';
@immutable
abstract class PublishEvent {}
class PublishStory extends PublishEvent {
final int categoryId;
PublishStory({
required this.categoryId,
});
}
class GetCategories extends PublishEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/stories/stories_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/decorations.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/loading.dart';
import 'package:jokes_app/common/widgets/not_found.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/profile/user_stories_screen.dart';
import 'package:jokes_app/ui/stories/bloc/stories_bloc.dart';
import 'package:jokes_app/ui/stories/story_category_item.dart';
import 'package:jokes_app/ui/view_story/view_story_screen.dart';
import 'package:lottie/lottie.dart';
import '../../common/widgets/story_item.dart';
class StoriesScreen extends StatefulWidget {
const StoriesScreen({super.key});
@override
State<StoriesScreen> createState() => _StoriesScreenState();
}
class _StoriesScreenState extends State<StoriesScreen> {
var selectedCategoryIndex = 0;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => StoriesBloc(injector.get())
..add(
GetCategories(),
),
child: BlocBuilder<StoriesBloc, StoriesState>(
builder: (context, state) {
final bloc = context.read<StoriesBloc>();
return Scaffold(
extendBodyBehindAppBar: true,
appBar: PreferredSize(
preferredSize: Size(context.width, 42),
child: (state.showCategories && state.categories.isNotEmpty)
? ListView.builder(
itemCount: state.categories.length,
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemBuilder: (e, i) {
final item = (state.categories)[i];
return StoryCategoryItem(
value: item,
selected: selectedCategoryIndex == i,
onTap: () {
bloc.add(GetCategoryStories(categoryId: item.id));
setState(
() {
selectedCategoryIndex = i;
},
);
},
);
},
)
: Container(),
),
body: Container(
height: context.height,
width: context.width,
decoration: const DefaultBackgroundDecoration(),
child: (state.stories.isEmpty)
? state.storiesStatus == StoriesStatus.success
? const NotFound()
: const Loading()
: ListView.builder(
controller: bloc.scrollController,
physics: const BouncingScrollPhysics(),
itemCount: state.stories.length,
itemBuilder: (e, i) {
final item = (state.stories)[i];
return StoryItem(
onTap: () {
context.navigateTo(
ViewStoryScreen(
story: item,
onReadFinish: () {
bloc.add(SetAsRead(storyId: item.id));
},
onUnpublish: () {
//
},
),
);
},
story: item,
onTapOwner: () {
context.navigateTo(UserStoriesScreen(
userId: item.authorId,
username: item.authorName,
));
},
);
},
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/stories/story_category_item.dart
|
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/domain/models/ui/category.dart';
class StoryCategoryItem extends StatelessWidget {
final Category value;
final bool selected;
final Function() onTap;
@override
Widget build(BuildContext context) {
return ScaleTap(
onPressed: () {
onTap.call();
},
child: Container(
margin: const EdgeInsets.only(left: 12, top: 4),
alignment: Alignment.center,
padding: const EdgeInsets.only(left: 16, right: 16),
height: 4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
color: selected ? AppColors.whiteAlpha52 : AppColors.darkGreen,
),
child: Text(
value.name.toLowerCase(),
style: primaryTextStyle(color: AppColors.white),
),
),
);
}
const StoryCategoryItem({
super.key,
required this.value,
required this.selected,
required this.onTap,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/stories
|
mirrored_repositories/stories-app/lib/ui/stories/bloc/stories_event.dart
|
part of 'stories_bloc.dart';
@immutable
abstract class StoriesEvent {}
class GetStories extends StoriesEvent {}
class GetCategoryStories extends StoriesEvent {
final int? categoryId;
GetCategoryStories({
this.categoryId,
});
}
class GetCategories extends StoriesEvent {}
class SetAsRead extends StoriesEvent {
final int storyId;
SetAsRead({
required this.storyId,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/stories
|
mirrored_repositories/stories-app/lib/ui/stories/bloc/stories_state.dart
|
part of 'stories_bloc.dart';
enum StoriesStatus { success, fail, loading }
class StoriesState extends Equatable {
final StoriesStatus? storiesStatus;
final List<Story> stories;
final StoriesStatus? categoryStatus;
final List<Category> categories;
final bool showCategories;
final int? categoryId;
@override
List<Object?> get props => [
storiesStatus,
categoryStatus,
stories,
categories,
showCategories,
categoryId
];
const StoriesState({
this.storiesStatus,
this.stories = const [],
this.categoryStatus,
this.categories = const [],
this.showCategories = true,
this.categoryId,
});
StoriesState copyWith({
StoriesStatus? storiesStatus,
List<Story>? stories,
StoriesStatus? categoryStatus,
List<Category>? categories,
bool? showCategories,
int? categoryId,
}) {
return StoriesState(
storiesStatus: storiesStatus ?? this.storiesStatus,
stories: stories ?? this.stories,
categoryStatus: categoryStatus ?? this.categoryStatus,
categories: categories ?? this.categories,
showCategories: showCategories ?? this.showCategories,
categoryId: categoryId ?? this.categoryId,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/stories
|
mirrored_repositories/stories-app/lib/ui/stories/bloc/stories_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/common/extensions/controller_ext.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:jokes_app/domain/models/ui/category.dart';
import '../../../domain/models/ui/story.dart';
import '../../../domain/repositories/stories_repository.dart';
part 'stories_event.dart';
part 'stories_state.dart';
class StoriesBloc extends Bloc<StoriesEvent, StoriesState> {
final StoriesRepository _repository;
final ScrollController scrollController = ScrollController();
int page = 1;
bool endOfPaginationReached = false;
StoriesBloc(this._repository) : super(const StoriesState()) {
on<GetStories>(_getStories);
on<GetCategories>(_getCategories);
on<GetCategoryStories>(_getCategoryStories);
on<SetAsRead>(_setAsRead);
scrollController.addListener(() {
if (state.showCategories == true) {
emit(state.copyWith(showCategories: false));
}
});
scrollController.onTopReached((onTop) {
emit(state.copyWith(showCategories: onTop));
});
scrollController.onBottomReached(() {
if (!endOfPaginationReached) {
page++;
add(GetStories());
}
});
}
Future<void> _getCategoryStories(
GetCategoryStories event, Emitter emitter) async {
page = 1;
emitter(state.copyWith(stories: [], categoryId: event.categoryId));
add(GetStories());
}
Future<void> _setAsRead(SetAsRead event, Emitter emitter) async {
_repository.setAsRead(event.storyId);
}
Future<void> _getStories(GetStories event, Emitter emitter) {
return emitter.forEach(
_repository.getStories(state.categoryId, page),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(storiesStatus: StoriesStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(storiesStatus: StoriesStatus.fail);
}
if (data is DomainSuccess<List<Story>>) {
endOfPaginationReached = ((data.data?.length ?? 0) < 10);
return state.copyWith(
storiesStatus: StoriesStatus.success,
stories: (state.stories) + (data.data ?? []));
}
return state;
},
);
}
Future<void> _getCategories(GetCategories event, Emitter emitter) {
return emitter.forEach(
_repository.getCategories(),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(categoryStatus: StoriesStatus.loading);
}
if (data is DomainFail) {
return state.copyWith(categoryStatus: StoriesStatus.fail);
}
if (data is DomainSuccess<List<Category>>) {
emitter(state.copyWith(categoryId: data.data?.first.id ?? 1));
add(GetStories());
return state.copyWith(
categoryStatus: StoriesStatus.success, categories: data.data);
}
return state;
},
);
}
}
| 0
|
mirrored_repositories/stories-app
|
mirrored_repositories/stories-app/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 in the flutter_test package. 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:jokes_app/main.dart';
void main() {
group('description', () {
test('description', () {
//
});
});
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter
|
mirrored_repositories/flutter-game-teddy-hunter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:teddyhunt/common/app_colors.dart';
import 'package:teddyhunt/ui/map_screen.dart';
void main() async {
Widget _defaultHome = new MapScreen();
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(
new MaterialApp(
color: AppColors.mainAppColor,
debugShowCheckedModeBanner: false,
title: 'Deliverit',
home: _defaultHome,
routes: {
MapScreen.tag: (context) => MapScreen(),
},
),
);
});
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/models/response_get_check_in.dart
|
// To parse this JSON data, do
//
// final responseGetCheckIn = responseGetCheckInFromJson(jsonString);
import 'dart:convert';
ResponseGetCheckIn responseGetCheckInFromJson(String str) => ResponseGetCheckIn.fromJson(json.decode(str));
String responseGetCheckInToJson(ResponseGetCheckIn data) => json.encode(data.toJson());
class ResponseGetCheckIn {
int s;
String m;
Rs rs;
ResponseGetCheckIn({
this.s,
this.m,
this.rs,
});
factory ResponseGetCheckIn.fromJson(Map<String, dynamic> json) => ResponseGetCheckIn(
s: json["s"] == null ? null : json["s"],
m: json["m"] == null ? null : json["m"],
rs: json["rs"] == null ? null : Rs.fromJson(json["rs"]),
);
Map<String, dynamic> toJson() => {
"s": s == null ? null : s,
"m": m == null ? null : m,
"rs": rs == null ? null : rs.toJson(),
};
}
class Rs {
String deviceCheckinsCount;
String allCheckinsCount;
List<LocationViewData> locations;
Rs({
this.deviceCheckinsCount,
this.allCheckinsCount,
this.locations,
});
factory Rs.fromJson(Map<String, dynamic> json) => Rs(
deviceCheckinsCount: json["device_checkins_count"] == null ? null : json["device_checkins_count"],
allCheckinsCount: json["all_checkins_count"] == null ? null : json["all_checkins_count"],
locations: json["locations"] == null ? null : List<LocationViewData>.from(json["locations"].map((x) => LocationViewData.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"device_checkins_count": deviceCheckinsCount == null ? null : deviceCheckinsCount,
"all_checkins_count": allCheckinsCount == null ? null : allCheckinsCount,
"locations": locations == null ? null : List<dynamic>.from(locations.map((x) => x.toJson())),
};
}
class LocationViewData {
String id;
String location;
String locLat;
String locLong;
String status;
DateTime createdAt;
DateTime updatedAt;
int deviceCheckinStatus;
LocationViewData({
this.id,
this.location,
this.locLat,
this.locLong,
this.status,
this.createdAt,
this.updatedAt,
this.deviceCheckinStatus,
});
factory LocationViewData.fromJson(Map<String, dynamic> json) => LocationViewData(
id: json["id"] == null ? null : json["id"],
location: json["location"] == null ? null : json["location"],
locLat: json["loc_lat"] == null ? null : json["loc_lat"],
locLong: json["loc_long"] == null ? null : json["loc_long"],
status: json["status"] == null ? null : json["status"],
createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
deviceCheckinStatus: json["device_checkin_status"] == null ? null : json["device_checkin_status"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"location": location == null ? null : location,
"loc_lat": locLat == null ? null : locLat,
"loc_long": locLong == null ? null : locLong,
"status": status == null ? null : status,
"created_at": createdAt == null ? null : createdAt.toIso8601String(),
"updated_at": updatedAt == null ? null : updatedAt.toIso8601String(),
"device_checkin_status": deviceCheckinStatus == null ? null : deviceCheckinStatus,
};
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/api/url_utils.dart
|
class URL {
static final String baseUrl =
"https://teddyhunthq.com/rest/index.php";
static final String addLocation = '$baseUrl/addLocation';
static final String getLocations = '$baseUrl/getLocations';
static final String addCheckIn = '$baseUrl/addCheckIn';
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/api/api_utils.dart
|
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
class ApiUtils {
static Dio dio = new Dio();
Future<dynamic> get(BuildContext context, String url) async {
debugPrint("GET URL : $url");
return dio
.get(
url,
)
.then((response) => onResponse(context, response));
}
Future<dynamic> post(BuildContext context, String url,
{Map<String, String> body}) async {
debugPrint("POST URL : $url");
debugPrint("Request body : $body");
return dio
.post(
url,
data: FormData.fromMap(body),
)
.then((response) => onResponse(context, response));
}
Future<dynamic> put(BuildContext context, String url,
{Map<String, String> body}) async {
debugPrint("PUT URL : $url");
debugPrint("Request body : $body");
return dio
.put(
url,
data: FormData.fromMap(body),
)
.then((response) => onResponse(context, response));
}
onResponse(BuildContext context, Response<dynamic> response) {
int code = response.statusCode;
var resData = response.data;
debugPrint("Response body : $code..." + response.data.toString());
if (code < 200 || code > 400) {
throw new Exception("Server Error...");
}
return json.decode(json.encode(resData));
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/common/toast_util.dart
|
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class AlertToast {
static void showToastMsg(String txt) {
Fluttertoast.showToast(
msg: txt,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 5,
backgroundColor: Colors.black54,
textColor: Colors.white,
);
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/common/shared_preferences.dart
|
import 'package:shared_preferences/shared_preferences.dart';
class Preferences {
static final String pfShowHelp = "showHelp";
static Future<bool> setString(String key, String data) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString(key, data);
}
static Future<String> getString(String key) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/common/app_colors.dart
|
import 'package:flutter/material.dart';
class AppColors {
static const Color mainAppColor = Color(0xff09dfbf);
static const Color buttonColor = Color(0xffdafaf5);
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/common/utils.dart
|
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:teddyhunt/common/app_colors.dart';
class TeddyHuntUtils {
static Future<String> getUUID() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
if (Platform.isIOS) {
IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
return iosDeviceInfo.identifierForVendor; // unique ID on iOS
} else if (Platform.isAndroid) {
AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
return androidDeviceInfo.androidId; // unique ID on Android
} else {
return "";
}
}
static Widget progressIndicator() {
return Container(
height: 55,
child: Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation<Color>(
AppColors.mainAppColor,
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/ui/place_picker_screen.dart
|
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:teddyhunt/api/api_utils.dart';
import 'package:teddyhunt/api/url_utils.dart';
import 'package:teddyhunt/common/app_colors.dart';
import 'package:teddyhunt/common/toast_util.dart';
import 'package:teddyhunt/common/utils.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
class LocationResult {
String name;
String locality;
LatLng latLng;
String formattedAddress;
String placeId;
}
class NearbyPlace {
String name;
String icon;
LatLng latLng;
}
class AutoCompleteItem {
String id;
String text;
int offset;
int length;
}
class PlacePicker extends StatefulWidget {
final String apiKey;
final LatLng displayLocation;
PlacePicker(this.apiKey, {this.displayLocation});
@override
State<StatefulWidget> createState() {
return PlacePickerState();
}
}
class PlacePickerState extends State<PlacePicker> {
final Completer<GoogleMapController> mapController = Completer();
final Set<Marker> markers = Set();
LocationResult locationResult;
OverlayEntry overlayEntry;
List<NearbyPlace> nearbyPlaces = List();
String sessionToken = Uuid().v4();
GlobalKey appBarKey = GlobalKey();
bool hasSearchTerm = false;
String previousSearchTerm = '';
int _mapTypeSelection = 0;
CameraPosition _cameraPosition;
ProgressDialog pr;
Map<int, Widget> _mapType = {
0: Padding(
padding: new EdgeInsets.fromLTRB(25, 1, 25, 1),
child: Text("Normal"),
),
1: Padding(
padding: new EdgeInsets.fromLTRB(25, 1, 25, 1),
child: Text("Satellite"),
),
};
PlacePickerState();
void onMapCreated(GoogleMapController controller) {
this.mapController.complete(controller);
moveToCurrentUserLocation();
}
@override
void setState(fn) {
if (this.mounted) {
super.setState(fn);
}
}
@override
void initState() {
super.initState();
pr = new ProgressDialog(context);
pr.style(message: "Please wait...");
markers.add(Marker(
position: widget.displayLocation ?? LatLng(23.4241, 53.8478),
markerId: MarkerId("selected-location"),
));
}
@override
void dispose() {
this.overlayEntry?.remove();
super.dispose();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: (){
return null;
},
child: Scaffold(
appBar: AppBar(
backgroundColor: AppColors.mainAppColor,
key: this.appBarKey,
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Platform.isIOS?
Icon(Icons.arrow_back_ios):
Icon(Icons.arrow_back),
),
title: SearchInput((it) {
searchPlace(it);
}),
centerTitle: true,
),
body: Column(
children: <Widget>[
Expanded(
child: GoogleMap(
mapType:
_mapTypeSelection == 0 ? MapType.normal : MapType.satellite,
initialCameraPosition: CameraPosition(
target: widget.displayLocation ?? LatLng(23.4241, 53.8478),
zoom: 15,
),
myLocationEnabled: true,
myLocationButtonEnabled: true,
onMapCreated: onMapCreated,
onTap: (latLng) {
clearOverlay();
moveToLocation(latLng, zoom: _cameraPosition.zoom);
},
markers: markers,
onCameraMove: (CameraPosition position) {
_cameraPosition = position;
},
),
),
this.hasSearchTerm
? SizedBox()
: Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SelectPlaceAction(
getLocationName(),
() {
if (this.locationResult != null){
_addCheckIn();
}
},
),
Divider(
height: 5,
),
Center(
child: Padding(
padding: EdgeInsets.all(15),
child: InkWell(
onTap: (){
openInsta();
},
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.buttonColor,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Colors.grey, width: 0.5)
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
width: 30,
height: 30,
child: Image.asset("assets/instagram.png"),
),
SizedBox(width: 10,),
Column(
children: <Widget>[
Text("SEND US SCORES", style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14),),
Text("AND TEDDY PICS", style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14),),
],
),
],
),
),
),
),
)
/*Expanded(
child: ListView(
children: this
.nearbyPlaces
.map(
(it) => NearbyPlaceItem(
it,
() {
moveToLocation(it.latLng);
},
),
)
.toList(),
),
),*/
],
),
),
],
),
),
);
}
/// Hides the autocomplete overlay
void clearOverlay() {
if (this.overlayEntry != null) {
this.overlayEntry.remove();
this.overlayEntry = null;
}
}
void searchPlace(String place) {
if (place == this.previousSearchTerm) {
return;
} else {
previousSearchTerm = place;
}
if (context == null) {
return;
}
clearOverlay();
setState(() {
hasSearchTerm = place.length > 0;
});
if (place.length < 1) {
return;
}
final RenderBox renderBox = context.findRenderObject();
Size size = renderBox.size;
final RenderBox appBarBox =
this.appBarKey.currentContext.findRenderObject();
this.overlayEntry = OverlayEntry(
builder: (context) => Positioned(
top: appBarBox.size.height,
width: size.width,
child: Material(
elevation: 1,
child: Container(
padding: EdgeInsets.symmetric(
vertical: 16,
horizontal: 24,
),
child: Row(
children: <Widget>[
SizedBox(
height: 24,
width: 24,
child: CircularProgressIndicator(
strokeWidth: 3,
),
),
SizedBox(
width: 24,
),
Expanded(
child: Text(
"Finding place...",
style: TextStyle(
fontSize: 16,
),
),
)
],
),
),
),
),
);
Overlay.of(context).insert(this.overlayEntry);
autoCompleteSearch(place);
}
void autoCompleteSearch(String place) {
place = place.replaceAll(" ", "+");
var endpoint =
"https://maps.googleapis.com/maps/api/place/autocomplete/json?" +
"key=${widget.apiKey}&" +
"input={$place}&sessiontoken=${this.sessionToken}";
if (this.locationResult != null) {
endpoint += "&location=${this.locationResult.latLng.latitude}," +
"${this.locationResult.latLng.longitude}";
}
http.get(endpoint).then((response) {
if (response.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(response.body);
List<dynamic> predictions = data['predictions'];
List<RichSuggestion> suggestions = [];
if (predictions.isEmpty) {
AutoCompleteItem aci = AutoCompleteItem();
aci.text = "No result found";
aci.offset = 0;
aci.length = 0;
suggestions.add(RichSuggestion(aci, () {}));
} else {
for (dynamic t in predictions) {
AutoCompleteItem aci = AutoCompleteItem();
aci.id = t['place_id'];
aci.text = t['description'];
aci.offset = t['matched_substrings'][0]['offset'];
aci.length = t['matched_substrings'][0]['length'];
suggestions.add(RichSuggestion(aci, () {
FocusScope.of(context).requestFocus(FocusNode());
decodeAndSelectPlace(aci.id);
}));
}
}
displayAutoCompleteSuggestions(suggestions);
}
}).catchError((error) {
print(error);
});
}
void decodeAndSelectPlace(String placeId) {
clearOverlay();
String endpoint =
"https://maps.googleapis.com/maps/api/place/details/json?key=${widget.apiKey}" +
"&placeid=$placeId";
http.get(endpoint).then((response) {
if (response.statusCode == 200) {
Map<String, dynamic> location =
jsonDecode(response.body)['result']['geometry']['location'];
LatLng latLng = LatLng(location['lat'], location['lng']);
moveToLocation(latLng);
}
}).catchError((error) {
print(error);
});
}
void displayAutoCompleteSuggestions(List<RichSuggestion> suggestions) {
final RenderBox renderBox = context.findRenderObject();
Size size = renderBox.size;
final RenderBox appBarBox =
this.appBarKey.currentContext.findRenderObject();
clearOverlay();
this.overlayEntry = OverlayEntry(
builder: (context) => Positioned(
width: size.width,
top: appBarBox.size.height,
child: Material(
elevation: 1,
child: Column(
children: suggestions,
),
),
),
);
Overlay.of(context).insert(this.overlayEntry);
}
String getLocationName() {
if (this.locationResult == null) {
return "Unnamed location";
}
for (NearbyPlace np in this.nearbyPlaces) {
if (np.latLng == this.locationResult.latLng &&
np.name != this.locationResult.locality) {
this.locationResult.name = np.name;
return "${np.name}, ${this.locationResult.locality}";
}
}
return "${this.locationResult.name}, ${this.locationResult.locality}";
}
/// Moves the marker to the indicated lat,lng
void setMarker(LatLng latLng) {
// markers.clear();
setState(() {
markers.clear();
markers.add(
Marker(
markerId: MarkerId("selected-location"),
position: latLng,
),
);
});
}
void getNearbyPlaces(LatLng latLng) {
http
.get("https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
"key=${widget.apiKey}&" +
"location=${latLng.latitude},${latLng.longitude}&radius=150")
.then((response) {
if (response.statusCode == 200) {
this.nearbyPlaces.clear();
for (Map<String, dynamic> item
in jsonDecode(response.body)['results']) {
NearbyPlace nearbyPlace = NearbyPlace();
nearbyPlace.name = item['name'];
nearbyPlace.icon = item['icon'];
double latitude = item['geometry']['location']['lat'];
double longitude = item['geometry']['location']['lng'];
LatLng _latLng = LatLng(latitude, longitude);
nearbyPlace.latLng = _latLng;
this.nearbyPlaces.add(nearbyPlace);
}
}
// to update the nearby places
setState(() {
// this is to require the result to show
this.hasSearchTerm = false;
});
}).catchError((error) {});
}
void reverseGeocodeLatLng(LatLng latLng) {
http
.get("https://maps.googleapis.com/maps/api/geocode/json?" +
"latlng=${latLng.latitude},${latLng.longitude}&" +
"key=${widget.apiKey}")
.then((response) {
if (response.statusCode == 200) {
Map<String, dynamic> responseJson = jsonDecode(response.body);
final result = responseJson['results'][0];
String road = result['address_components'][0]['short_name'];
String locality = result['address_components'][1]['short_name'];
setState(() {
this.locationResult = LocationResult();
this.locationResult.name = road;
this.locationResult.locality = locality;
this.locationResult.latLng = latLng;
this.locationResult.formattedAddress = result['formatted_address'];
this.locationResult.placeId = result['place_id'];
});
}
}).catchError((error) {
print(error);
});
}
void moveToLocation(LatLng latLng, {double zoom}) {
this.mapController.future.then((controller) {
controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: latLng,
zoom: zoom == null ? 15.0 : zoom,
),
),
);
});
setMarker(latLng);
reverseGeocodeLatLng(latLng);
getNearbyPlaces(latLng);
}
void moveToCurrentUserLocation() {
if (widget.displayLocation != null) {
moveToLocation(widget.displayLocation);
return;
}
var location = Location();
location.getLocation().then((locationData) {
LatLng target = LatLng(locationData.latitude, locationData.longitude);
moveToLocation(target);
}).catchError((error) {
// TODO: Handle the exception here
print(error);
});
}
openInsta() async {
const url = 'https://urlgeni.us/instagram/tpv';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Future<void> _addCheckIn() async {
await pr.show();
Map<String, String> body = {
'device_id': await TeddyHuntUtils.getUUID(),
'location': this.locationResult.name,
'loc_lat': this.locationResult.latLng.latitude.toString(),
'loc_long': this.locationResult.latLng.longitude.toString(),
};
ApiUtils().post(context, URL.addLocation, body: body).then((response) {
pr.hide();
AlertToast.showToastMsg(response['m']);
Navigator.pop(context);
}).catchError((error) {
if (error.type == DioErrorType.DEFAULT) {
AlertToast.showToastMsg("No internet connection");
} else {
AlertToast.showToastMsg("Something went wrong");
}
});
}
}
class SearchInput extends StatefulWidget {
final ValueChanged<String> onSearchInput;
SearchInput(this.onSearchInput);
@override
State<StatefulWidget> createState() {
return SearchInputState();
}
}
class SearchInputState extends State<SearchInput> {
TextEditingController editController = TextEditingController();
Timer debouncer;
bool hasSearchEntry = false;
SearchInputState();
@override
void initState() {
super.initState();
this.editController.addListener(this.onSearchInputChange);
}
@override
void dispose() {
this.editController.removeListener(this.onSearchInputChange);
this.editController.dispose();
super.dispose();
}
void onSearchInputChange() {
if (this.editController.text.isEmpty) {
this.debouncer?.cancel();
widget.onSearchInput(this.editController.text);
return;
}
if (this.debouncer?.isActive ?? false) {
this.debouncer.cancel();
}
this.debouncer = Timer(Duration(milliseconds: 500), () {
widget.onSearchInput(this.editController.text);
});
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: 8,
),
child: Row(
children: <Widget>[
Icon(
Icons.search,
color: Theme.of(context).textTheme.body1.color,
),
SizedBox(
width: 8,
),
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: "Add a New Teddy Bear Location",
border: InputBorder.none,
),
controller: this.editController,
onChanged: (value) {
setState(() {
this.hasSearchEntry = value.isNotEmpty;
});
},
),
),
SizedBox(
width: 8,
),
this.hasSearchEntry
? GestureDetector(
child: Icon(
Icons.clear,
),
onTap: () {
this.editController.clear();
setState(() {
this.hasSearchEntry = false;
});
},
)
: SizedBox(),
],
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: Theme.of(context).canvasColor,
),
);
}
}
class SelectPlaceAction extends StatelessWidget {
String locationName;
final VoidCallback onTap;
SelectPlaceAction(this.locationName, this.onTap);
@override
Widget build(BuildContext context) {
locationName = locationName.replaceAll(", ", " ");
return Material(
child: InkWell(
onTap: () {
this.onTap();
},
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 24,
vertical: 16,
),
child: Row(
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
locationName,
style: TextStyle(
fontSize: 16,
),
),
Text(
"Tap to select this location",
style: TextStyle(
color: Colors.grey,
fontSize: 15,
),
),
],
),
),
/*Icon(
Icons.arrow_forward,
)*/
Text(
'ADD',
style: TextStyle(
color: AppColors.mainAppColor,
fontWeight: FontWeight.bold,
fontSize: 20,
),
)
],
),
),
),
);
}
}
class NearbyPlaceItem extends StatelessWidget {
final NearbyPlace nearbyPlace;
final VoidCallback onTap;
NearbyPlaceItem(this.nearbyPlace, this.onTap);
@override
Widget build(BuildContext context) {
return Material(
child: InkWell(
onTap: onTap,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 24,
vertical: 16,
),
child: Row(
children: <Widget>[
Image.network(
nearbyPlace.icon,
width: 16,
),
SizedBox(
width: 24,
),
Expanded(
child: Text(
"${nearbyPlace.name}",
style: TextStyle(
fontSize: 16,
),
),
)
],
)),
),
);
}
}
class RichSuggestion extends StatelessWidget {
final VoidCallback onTap;
final AutoCompleteItem autoCompleteItem;
RichSuggestion(this.autoCompleteItem, this.onTap);
@override
Widget build(BuildContext context) {
return Material(
child: InkWell(
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 24,
vertical: 16,
),
child: Row(
children: <Widget>[
Expanded(
child: RichText(
text: TextSpan(children: getStyledTexts(context)),
),
)
],
)),
onTap: this.onTap,
),
);
}
List<TextSpan> getStyledTexts(BuildContext context) {
final List<TextSpan> result = [];
String startText =
this.autoCompleteItem.text.substring(0, this.autoCompleteItem.offset);
if (startText.isNotEmpty) {
result.add(
TextSpan(
text: startText,
style: TextStyle(
color: Colors.grey,
fontSize: 15,
),
),
);
}
String boldText = this.autoCompleteItem.text.substring(
this.autoCompleteItem.offset,
this.autoCompleteItem.offset + this.autoCompleteItem.length);
result.add(TextSpan(
text: boldText,
style: TextStyle(
fontSize: 15,
color: Theme.of(context).textTheme.body1.color,
),
));
String remainingText = this
.autoCompleteItem
.text
.substring(this.autoCompleteItem.offset + this.autoCompleteItem.length);
result.add(
TextSpan(
text: remainingText,
style: TextStyle(
color: Colors.grey,
fontSize: 15,
),
),
);
return result;
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter/lib
|
mirrored_repositories/flutter-game-teddy-hunter/lib/ui/map_screen.dart
|
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:teddyhunt/api/api_utils.dart';
import 'package:teddyhunt/api/url_utils.dart';
import 'package:teddyhunt/common/app_colors.dart';
import 'package:teddyhunt/common/shared_preferences.dart';
import 'package:teddyhunt/common/toast_util.dart';
import 'package:teddyhunt/common/utils.dart';
import 'package:teddyhunt/models/response_get_check_in.dart';
import 'package:teddyhunt/ui/place_picker_screen.dart';
import 'package:url_launcher/url_launcher.dart';
class Place {
double latitude;
double longitude;
String address;
Place({
this.latitude,
this.longitude,
this.address,
});
}
class MapScreen extends StatefulWidget {
static String tag = "/map";
@override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
//Google map related
BitmapDescriptor iconBeforeCheckin;
BitmapDescriptor iconAfterCheckin;
String pfShowHelp;
Completer<GoogleMapController> _controller;
Set<Marker> _markers = {};
Position _currentLocation;
bool _isLoading = false;
ResponseGetCheckIn _responseGetCheckIn;
StreamSubscription<Position> _getPositionSubscription;
void _getLocation() async {
setState(() {
_isLoading = true;
});
_currentLocation = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
if (_currentLocation != null) {
if(pfShowHelp!=null){
updatePinOnMap();
_addLocationObserver();
_getCheckInRecords();
}else{
setState(() {
_isLoading = false;
});
}
}
}
int num = 0;
void _addLocationObserver() {
if (_getPositionSubscription == null) {
const LocationOptions locationOptions =
LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 5);
final Stream<Position> positionStream =
Geolocator().getPositionStream(locationOptions);
_getPositionSubscription = positionStream.listen((Position position) {
if (position != null) {
if(num == 0){
num = 1;
Future.delayed(Duration(seconds: 5), (){
_getCheckInRecords();
});
}
_currentLocation = position;
updatePinOnMap();
}
});
_getPositionSubscription.pause();
}
if (_getPositionSubscription.isPaused) {
_getPositionSubscription.resume();
} else {
_getPositionSubscription.pause();
}
setState(() {});
}
Future<void> _getCheckInRecords() async {
ApiUtils()
.get(context,
'${URL.getLocations}?device_id=${await TeddyHuntUtils.getUUID()}&loc_lat=${_currentLocation.latitude}&loc_long=${_currentLocation.longitude}')
.then((dynamic response) async {
num = 0;
if (response["s"] == 1) {
var res = ResponseGetCheckIn.fromJson(response);
_setMarkers(res);
} else {
setState(() {
_isLoading = false;
});
AlertToast.showToastMsg(response["m"]);
}
}).catchError((error) {
num = 0;
setState(() {
_isLoading = false;
});
if (error.type == DioErrorType.DEFAULT) {
AlertToast.showToastMsg("No internet connection");
} else {
AlertToast.showToastMsg("Something went wrong");
}
});
}
_setMarkers(ResponseGetCheckIn res) {
_markers.clear();
Set<Marker> _dummyMarkers = {};
if (res != null) {
for (int i = 0; i < res.rs.locations.length; i++) {
var item = res.rs.locations[i];
_dummyMarkers.add(
Marker(
markerId: MarkerId(item.id),
position: LatLng(
double.parse(item.locLat),
double.parse(item.locLong),
),
infoWindow: InfoWindow(
title: item.location,
),
onTap: () {
updatePinOnMap();
if (item.deviceCheckinStatus == 0) {
_addCheckIn(item.id);
}
},
icon: item.deviceCheckinStatus == 0
? iconBeforeCheckin
: iconAfterCheckin
/*icon: item.deviceCheckinStatus == 0
? BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueBlue,
)
: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueGreen,
),*/
),
);
}
}
_markers = _dummyMarkers;
_responseGetCheckIn = res;
_isLoading = false;
setState(() {});
}
_addCheckIn(String id) async {
Map<String, String> body = {
'device_id': await TeddyHuntUtils.getUUID(),
'location_id': id,
};
ApiUtils().post(context, URL.addCheckIn, body: body).then((response) {
AlertToast.showToastMsg(response['m']);
_getPositionSubscription = null;
_getLocation();
}).catchError((error) {
if (error.type == DioErrorType.DEFAULT) {
AlertToast.showToastMsg("No internet connection");
} else {
AlertToast.showToastMsg("Something went wrong");
}
});
}
Widget _topBody() {
return new Container(
color: AppColors.mainAppColor,
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Stack(
alignment: Alignment.bottomRight,
children: <Widget>[
Opacity(
opacity: 0.7,
child: Image.asset(
"assets/bg.png",
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width * 0.70,
),
),
Positioned(
left: 20.0,
top: 40.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
"TEDDY BANK",
style: new TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 26.0),
),
new Text(
_responseGetCheckIn != null
? "${_responseGetCheckIn.rs.deviceCheckinsCount}"
: "0",
style: new TextStyle(
color: Colors.white,
fontWeight: FontWeight.w800,
fontSize: 46.0),
),
],
),
)
],
),
);
}
Widget _mapBody() {
return ClipRRect(
borderRadius: new BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40),
),
child: new Container(
color: AppColors.mainAppColor,
child: Stack(
children: <Widget>[
GoogleMap(
scrollGesturesEnabled: false,
myLocationButtonEnabled: false,
myLocationEnabled: true,
zoomGesturesEnabled: false,
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(
_currentLocation?.latitude??35.9748787,
_currentLocation?.longitude??-79.085389,
),
zoom: 18,
),
markers: _markers,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
_getLocation();
},
),
new Container(
color: Colors.white.withOpacity(0.7),
height: 60,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
margin: EdgeInsets.only(left: 15, top: 5, bottom: 5),
height: 50,
decoration: BoxDecoration(
borderRadius: new BorderRadius.all(
Radius.circular(40),
),
color: AppColors.buttonColor,
),
child: Row(
children: <Widget>[
new SizedBox(
width: 15,
),
ClipOval(
child: Image.asset(
"assets/world.png",
height: 30,
width: 30,
),
),
new SizedBox(
width: 10,
),
new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
"TEDDY TALLY",
style: new TextStyle(
fontWeight: FontWeight.w500,
fontSize: 12,
),
),
new Text(
_responseGetCheckIn != null
? "${_responseGetCheckIn.rs.allCheckinsCount}"
: "0",
style: new TextStyle(
fontWeight: FontWeight.w800,
fontSize: 14,
),
),
],
),
new SizedBox(
width: 10,
),
],
),
),
InkWell(
onTap: (){
openGofundme();
},
child: new Container(
margin: EdgeInsets.only(right: 15, top: 1, bottom: 5),
alignment: Alignment.center,
height: 54,
width: 56,
decoration: BoxDecoration(
color: Colors.blue[100],
borderRadius: BorderRadius.circular(50)
),
child: Center(child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("DONATE", style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold),),
Text("TO C19", style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold),),
Text("RELIEF", style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold),)
],
),),
),
),
],
),
)
),
],
),
),
);
}
@override
void initState() {
super.initState();
_controller = Completer();
getHelpPref();
if(pfShowHelp == null){
_getLocation();
}
setBeforeCheckinPin();
setAfterCheckinPin();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Container(
color: AppColors.mainAppColor,
child: Column(
children: <Widget>[
_topBody(),
SizedBox(
child: new Container(
color: AppColors.mainAppColor,
),
height: 20,
),
Expanded(
child: pfShowHelp == null ? helpDialog() : _mapBody())
],
),
),
_isLoading
? Container(
color: Colors.white.withOpacity(0.3),
child: Center(
child: TeddyHuntUtils.progressIndicator(),
),
)
:Container()
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: AppColors.mainAppColor,
onPressed: () {
showPlacePicker();
},
child: new Icon(
Icons.add,
),
),
);
}
showPlacePicker() async {
Navigator.of(context)
.push(
MaterialPageRoute(
builder: (context) =>
PlacePicker("AIzaSyBaufeudiAD-D5OOKio76MB7wWGuQ2D6tY"),
),
)
.then((isReload) {
if (isReload == null) {
_getPositionSubscription = null;
_getLocation();
}
});
}
openGofundme() async {
const url = 'https://www.gofundme.com/f/teddy-hunt?utm_source=customer&utm_medium=copy_link&utm_campaign=p_cf+share-flow-1';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
void setBeforeCheckinPin() async {
iconBeforeCheckin = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 1.5), "assets/bear_dark.png");
}
void setAfterCheckinPin() async {
iconAfterCheckin = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 1.5), "assets/bear.png");
}
@override
void dispose() {
super.dispose();
if (_getPositionSubscription != null) {
_getPositionSubscription.cancel();
_getPositionSubscription = null;
}
debugPrint("Location listner removed");
}
getHelpPref() {
Preferences.getString(Preferences.pfShowHelp).then((onValue) {
setState(() {
pfShowHelp = onValue;
print("##$pfShowHelp");
});
});
}
Widget helpDialog() {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 0.0,
child: SingleChildScrollView(
child: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
"1. Find as many Bears and Rainbows in your neighborhood as you can and add them to your Teddy Bank by tapping on each Rainbow Bear! (Teddy Bank will reset nightly)",
style: TextStyle(fontSize: 20.0),
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
"2. If you see a bear or rainbow in a window that hasn't been mapped, hit the + button and add it!",
style: TextStyle(fontSize: 20.0),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: RaisedButton(
color: AppColors.mainAppColor,
onPressed: () {
Preferences.setString(Preferences.pfShowHelp, "true");
pfShowHelp = "true";
setState(() {});
},
child: Text('OK',
style: TextStyle(fontSize: 20, color: Colors.white)),
),
),
],
),
),
),
);
}
Future<void> updatePinOnMap() async {
double lat = _currentLocation.latitude;
CameraPosition cPosition = CameraPosition(
target: LatLng(
_currentLocation.latitude,
_currentLocation.longitude,
),
zoom: 18,
);
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(cPosition));
setState(() {});
}
}
| 0
|
mirrored_repositories/flutter-game-teddy-hunter
|
mirrored_repositories/flutter-game-teddy-hunter/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:teddyhunt/main.dart';
import 'package:teddyhunt/ui/map_screen.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MapScreen());
// 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/fitness_app
|
mirrored_repositories/fitness_app/lib/main.dart
|
import 'package:firebase_core/firebase_core.dart';
import 'package:fitness_app/Modules/ProfileSetup/profileSetup.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import '.firebase_options.dart';
import 'Modules/Authentication/Login/login.dart';
import 'Modules/Authentication/Welcome/welcome.dart';
import 'Modules/BNB/bottomNav.dart';
import 'Network/local/cacheHelper.dart';
import 'Shared/Constants/constants.dart';
import 'Shared/cubit/app_cubit.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await CacheHelper.init();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
late Widget home;
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
if (uid != null) {
home = BNB();
} else {
home = WelcomeScreen();
}
return BlocProvider(
create: (context) => AppCubit()..getUserProfile(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
scaffoldBackgroundColor: HexColor('E2E2E2'),
fontFamily: 'Poppins',
appBarTheme: AppBarTheme(
elevation: 0,
color: HexColor('E2E2E2'),
),
),
home: home,
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Network
|
mirrored_repositories/fitness_app/lib/Network/local/cacheHelper.dart
|
// ignore_for_file: unused_import
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CacheHelper {
static SharedPreferences? sharedPreferences;
static init() async {
sharedPreferences = await SharedPreferences.getInstance();
}
static Future<bool?> putBoolean({
required String key,
required bool value,
}) async {
return await sharedPreferences?.setBool(key, value);
}
static dynamic getData({
required String key,
}) {
print(sharedPreferences?.get(key));
return sharedPreferences?.get(key);
}
static Future<bool?> saveData({
required String key,
required dynamic value,
}) async {
if (value is String) return await sharedPreferences?.setString(key, value);
if (value is int) return await sharedPreferences?.setInt(key, value);
if (value is bool) return await sharedPreferences?.setBool(key, value);
return await sharedPreferences?.setDouble(key, value);
}
static Future<bool?> removeData({
required String key,
}) async {
return await sharedPreferences?.remove(key);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Exercises/exercises.dart
|
// ignore_for_file: must_be_immutable
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fitness_app/Modules/ExerciseDetails/exerciseDetails.dart';
import 'package:fitness_app/Modules/Exercises/exerciseSearch.dart';
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../Start Exercise/startExercise.dart';
class ExercisesScreen extends StatelessWidget {
const ExercisesScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {},
builder: (context, state) {
CollectionReference exercisesCollection =
FirebaseFirestore.instance.collection('exercises');
dynamic exercisesRef = exercisesCollection;
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
appBar: AppBar(
backgroundColor: HexColor('E2E2E2'),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
navigateTo(context, ExerciseSearchScreen());
},
),
settingsIcon(),
],
title: Text('Exercises',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
32.h,
Text('Recent',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
GestureDetector(
onTap: () {},
child: styledCard(
width: 320.0,
height: 130.0,
color: Colors.white,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
navigateToAndFinish(context, StartExercise());
},
child: Text('Start',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
HexColor('F2C70D'))),
),
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.topLeft,
child: PhosphorIcon(
PhosphorIconsFill.personSimpleRun,
size: 70,
color: Colors.black,
),
),
8.w,
Align(
alignment: Alignment.topCenter,
child: Text('Running',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
),
],
),
),
],
),
),
),
16.h,
GestureDetector(
onTap: () {},
child: styledCard(
width: 320.0,
height: 130.0,
color: Colors.white,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
navigateToAndFinish(context, StartExercise());
},
child: Text('Start',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
HexColor('F2C70D'))),
),
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.topLeft,
child: PhosphorIcon(
PhosphorIconsFill.bicycle,
size: 70,
color: Colors.black,
),
),
8.w,
Align(
alignment: Alignment.topCenter,
child: Text('Cycling',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
),
],
),
),
],
),
),
),
32.h,
Text('All',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
StreamBuilder<QuerySnapshot>(
stream: exercisesRef.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
final QuerySnapshot? querySnapshot = snapshot.data;
if (querySnapshot == null) {
print('DATA DOES NOT EXIST.');
return Text(
'No data available',
);
}
return ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) {
final DocumentSnapshot<Object?> document =
querySnapshot.docs[index];
return exerciseWidget(
name: document['name'],
equipment: document['equipment'],
focus: document['focus area'],
tips: document['tips'],
icon: document['icon'],
image: document['image']);
},
separatorBuilder: (context, index) => 16.h,
itemCount: querySnapshot.docs.length,
physics: NeverScrollableScrollPhysics(),
);
},
),
130.h,
],
),
),
),
);
},
);
}
}
class exerciseWidget extends StatelessWidget {
exerciseWidget({
super.key,
required this.name,
this.icon,
required this.equipment,
required this.focus,
required this.tips,
required this.image,
});
final name;
var icon;
final equipment;
final focus;
final tips;
final image;
@override
Widget build(BuildContext context) {
if (icon == 'lowerbody') {
icon = Image.asset('images/lowerBody.png');
} else if (icon == 'abs') {
icon = Image.asset('images/abs.png');
} else if (icon == 'upperbody') {
icon = Image.asset('images/upperBody.png');
}
return GestureDetector(
onTap: () {
navigateTo(
context,
ExerciseDetails(
name: name,
equipment: equipment,
focus: focus,
tips: tips,
image: image));
},
child: styledCard(
width: 320.0,
height: 130.0,
color: Colors.white,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
navigateToAndFinish(context, StartExercise());
},
child: Text('Start',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
),
),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.topLeft,
child: icon,
),
8.w,
Align(
alignment: Alignment.topCenter,
child: Text(name,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
),
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Exercises/exerciseSearch.dart
|
import 'package:fitness_app/Modules/Exercises/exercises.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/cubit/app_cubit.dart';
class ExerciseSearchScreen extends StatelessWidget {
const ExerciseSearchScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
print(state);
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(
top: 20.0, right: 20.0, left: 20.0),
child: Column(
children: [
TextField(
onChanged: (value) {
AppCubit.get(context).searchQuery = value;
},
onSubmitted: (value) {
AppCubit.get(context).performSearch();
},
decoration: InputDecoration(
hintText: 'Search',
),
),
],
),
),
),
SliverFillRemaining(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
children: [
40.h,
ListView.separated(
shrinkWrap: true,
separatorBuilder: (context, index) => 20.h,
physics: NeverScrollableScrollPhysics(),
itemCount:
AppCubit.get(context).searchResults.length,
itemBuilder: (BuildContext context, int index) {
final docSnapshot =
AppCubit.get(context).searchResults[index];
// Display the relevant data from the document snapshot
return exerciseWidget(
name: docSnapshot['name'],
equipment: docSnapshot['equipment'],
focus: docSnapshot['focus area'],
tips: docSnapshot['tips'],
icon: docSnapshot['icon'],
image: docSnapshot['image']);
},
),
40.h,
],
),
),
),
)
],
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Meal Recipe/mealRecipe.dart
|
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../SwapMeals/swapMeals.dart';
class MealRecipe extends StatelessWidget {
const MealRecipe({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
appBar: AppBar(
elevation: 0,
backgroundColor: HexColor("E2E2E2"),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
styledCard(
height: 255.0,
width: 320.0,
color: Colors.white,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.network(
'https://www.budgetbytes.com/wp-content/uploads/2019/06/Lemon-Berry-Yogurt-Breakfast-Bowls-stirred.jpg',
fit: BoxFit.fill,
),
),
),
24.h,
Text('Berry Yogurt',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
32.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 60.0),
child: Row(
children: [
Column(
children: [
PhosphorIcon(
PhosphorIconsFill.fire,
size: 48,
color: Color(0xFF6E6E6E),
),
8.h,
Text('340 kcal',
style: TextStyle(
color: HexColor('6E6E6E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
Spacer(),
Container(
height: 77,
width: 1,
color: HexColor('C5C5C5'),
),
Spacer(),
Column(
children: [
PhosphorIcon(
PhosphorIconsFill.clockAfternoon,
size: 48,
color: Color(0xFF6E6E6E),
),
8.h,
Text('14m',
style: TextStyle(
color: HexColor('6E6E6E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
],
),
),
48.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('INGREDIENTS',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
Text('• Maintain an upright posture',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text('• Run on soft surface to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text('• Take short strides to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
),
),
32.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('INSTRUCTIONS',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
Text('• Maintain an upright posture',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text('• Run on soft surface to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text('• Take short strides to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
32.h,
TextButton(
onPressed: () {
navigateTo(context, SwapMealsScreen());
},
child: Text('Swap',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
minimumSize:
MaterialStatePropertyAll(Size(320, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
),48.h,
],
),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Meals/meals.dart
|
import 'package:fitness_app/Modules/Meal%20Recipe/mealRecipe.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/Components/components.dart';
class MealsScreen extends StatelessWidget {
const MealsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: HexColor('E2E2E2'),
actions: [
settingsIcon(),],
title: Text('Meal Plan',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
body: Column(
children: [
32.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GestureDetector(
onTap: () {
navigateTo(context, MealRecipe());
},
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.sun,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Breakfast',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'Berry Yogurt',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
overflow: TextOverflow.fade,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
const Text(
'340 kcal',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const PhosphorIcon(
PhosphorIconsFill.dot,
size: 15,
color: Color(0xFF6E6E6E),
),
const Text(
'View Recipe',
style: TextStyle(
color: Colors.black,
fontSize: 14,
decoration: TextDecoration.underline,
fontWeight: FontWeight.w500,
),
),
8.w,
const PhosphorIcon(
PhosphorIconsFill.arrowRight,
size: 15,
color: Colors.black,
),
],
)
],
),
8.h,
],
)
],
)),
),
),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GestureDetector(
onTap: () {
navigateTo(context, MealRecipe());
},
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.clockAfternoon,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Afternoon',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'Berry Yogurt',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
overflow: TextOverflow.fade,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
const Text(
'340 kcal',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const PhosphorIcon(
PhosphorIconsFill.dot,
size: 15,
color: Color(0xFF6E6E6E),
),
const Text(
'View Recipe',
style: TextStyle(
color: Colors.black,
fontSize: 14,
decoration: TextDecoration.underline,
fontWeight: FontWeight.w500,
),
),
8.w,
const PhosphorIcon(
PhosphorIconsFill.arrowRight,
size: 15,
color: Colors.black,
),
],
)
],
),
8.h,
],
)
],
)),
),
),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: GestureDetector(
onTap: () {
navigateTo(context, MealRecipe());
},
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.moon,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Night',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'Berry Yogurt',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
overflow: TextOverflow.fade,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
const Text(
'340 kcal',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const PhosphorIcon(
PhosphorIconsFill.dot,
size: 15,
color: Color(0xFF6E6E6E),
),
const Text(
'View Recipe',
style: TextStyle(
color: Colors.black,
fontSize: 14,
decoration: TextDecoration.underline,
fontWeight: FontWeight.w500,
),
),
8.w,
const PhosphorIcon(
PhosphorIconsFill.arrowRight,
size: 15,
color: Colors.black,
),
],
)
],
),
8.h,
],
)
],
)),
),
),
16.h,
],
),
backgroundColor: HexColor('E2E2E2'),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/AdminPanel/admin.dart
|
// ignore_for_file: prefer_const_constructors
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/cubit/app_cubit.dart';
import '../Start Exercise/startExercise.dart';
class AdminPanel extends StatelessWidget {
const AdminPanel({super.key});
@override
Widget build(BuildContext context) {
// EXERCISE CONTROLLERS
var exerciseNameController = TextEditingController();
var exerciseFocusController = TextEditingController();
var exerciseEquipmentController = TextEditingController();
var exerciseTipsController = TextEditingController();
var exerciseImageController = TextEditingController();
var cubit = AppCubit.get(context);
// MEAL CONTROLLERS
var mealNameController = TextEditingController();
var mealTimeController = TextEditingController();
var mealCaloriesController = TextEditingController();
var mealDietController = TextEditingController();
var mealImageController = TextEditingController();
var mealIngredientsController = TextEditingController();
var mealInstructionsController = TextEditingController();
return Scaffold(
appBar: AppBar(
title: Text('Admin Panel',
style: TextStyle(
fontSize: 32,
color: HexColor('2E2E2E'),
fontWeight: FontWeight.w600,
)),
centerTitle: true,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.h,
Text('Add a new exercise',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
8.h,
styledCard(
width: 320.0,
height: 466.0,
color: Colors.white,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
const Align(
alignment: Alignment.topLeft,
child: PhosphorIcon(
PhosphorIconsFill.bicycle,
size: 70,
color: Colors.black,
),
),
8.w,
Align(
alignment: Alignment.topCenter,
child: SizedBox(
width: 100,
child: TextField(
controller: exerciseNameController,
))),
],
),
),
Spacer(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Focus Area',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: exerciseFocusController,
),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Equipment',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: exerciseEquipmentController,
),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Tips',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child:
TextField(controller: exerciseTipsController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Image',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child:
TextField(controller: exerciseImageController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.all(10.0),
child: Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
List<String> tips =
exerciseTipsController.text.split(',');
cubit.addExercise(
name: exerciseNameController.text,
focusArea: exerciseFocusController.text,
equipment: exerciseEquipmentController.text,
tips: tips,
image: exerciseImageController.text,
context: context);
},
style: ButtonStyle(
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
child: const Text('Add',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
),
),
),
Spacer(),
],
),
),
32.h,
Text('Add a new meal',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
8.h,
styledCard(
width: 320.0,
height: 466.0 + 56,
color: Colors.white,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
const Align(
alignment: Alignment.topLeft,
child: PhosphorIcon(
PhosphorIconsFill.bowlFood,
size: 70,
color: Colors.black,
),
),
8.w,
Align(
alignment: Alignment.topCenter,
child: SizedBox(
width: 100,
child: TextField(
controller: mealNameController,
))),
],
),
),
Spacer(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Diet',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: mealDietController,
),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Image',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: mealImageController,
),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Ingredients',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: mealIngredientsController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Instructions',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(
controller: mealInstructionsController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Time',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child: TextField(controller: mealTimeController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Text('Calories',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
)),
Spacer(),
SizedBox(
width: 100,
child:
TextField(controller: mealCaloriesController),
),
],
),
),
8.h,
Padding(
padding: const EdgeInsets.all(10.0),
child: Align(
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
List<String> ingredients =
mealIngredientsController.text.split(',');
List<String> instructions =
mealInstructionsController.text.split(',');
cubit.addMeal(
diet: mealDietController.text,
image: mealImageController.text,
name: mealNameController.text,
time: mealTimeController.text,
calories: mealCaloriesController.text,
ingredients: ingredients,
instructions: instructions,
context: context);
},
style: ButtonStyle(
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
child: const Text('Add',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
),
),
),
Spacer(),
],
),
),
20.h,
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Settings/settings.dart
|
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/Components/components.dart';
import '../../Shared/Constants/constants.dart';
class SettingsScreen extends StatelessWidget {
SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
var cubit = AppCubit.get(context);
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
backgroundColor: HexColor('E2E2E2'),
title: Text('Settings',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
children: [
32.h,
Row(
children: [
GestureDetector(
onTap: () {
cubit.changeUnit(true);
},
child: styledCard(
color:
metricUnits ? HexColor('F2C70D') : Colors.white,
width: 150.0,
height: 75.0,
child: Center(
child: Text('KG/CM',
style: TextStyle(
color:
metricUnits ? Colors.white : Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
),
),
),
16.w,
GestureDetector(
onTap: () {
cubit.changeUnit(false);
},
child: styledCard(
color:
metricUnits ? Colors.white : HexColor('F2C70D'),
width: 150.0,
height: 75.0,
child: Center(
child: Text('IB/FT',
style: TextStyle(
color:
metricUnits ? Colors.black : Colors.white,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
),
),
),
],
),
16.h,
styledCard(
color: Colors.white,
width: 320.0,
height: 228.0 + 8,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const Align(
alignment: Alignment.topLeft,
child: Text('Profile',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 32,
)),
),
16.h,
Row(
children: [
const Text('Weight',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
Text('${cubit.weight} ${cubit.weightUnit}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretUpDown,
size: 27,
color: Colors.black,
),
],
),
8.h,
Row(
children: [
const Text('Height',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
Text('${cubit.height} ${cubit.lenghtUnit}',
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretUpDown,
size: 27,
color: Colors.black,
),
],
),
8.h,
Row(
children: [
const Text('Gender',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
Text('${cubit.gender}',
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretDown,
size: 27,
color: Colors.black,
),
],
),
8.h,
],
),
),
),
32.h,
styledCard(
color: Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
const Align(
alignment: Alignment.center,
child: Text('Diet Plan',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
const Spacer(),
Align(
alignment: Alignment.center,
child: Text('${cubit.diet}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretDown,
size: 27,
color: Colors.black,
),
],
),
),
),
16.h,
styledCard(
color: Colors.white,
width: 320.0,
height: 124.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Row(
children: [
const Text('Goal',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
Text('${cubit.goal}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretDown,
size: 27,
color: Colors.black,
),
],
),
8.h,
Row(
children: [
const Text('Target Weight',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
Text('',
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
8.w,
const PhosphorIcon(
PhosphorIconsFill.caretUpDown,
size: 27,
color: Colors.black,
),
],
),
],
),
),
),
32.h,
GestureDetector(
onTap: () {
cubit.logout(context);
},
child: styledCard(
color: Colors.red,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
const Align(
alignment: Alignment.center,
child: Text('Logout',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
const Spacer(),
8.w,
const PhosphorIcon(
PhosphorIconsFill.signOut,
size: 27,
color: Colors.white,
),
],
),
),
),
),
16.h,
Text('UID: $uid'),
32.h,
],
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/ProfileSetup/profileSetup.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/Components/components.dart';
import '../../Shared/cubit/app_cubit.dart';
var _goal;
var _diet;
var _gender;
var _height;
var _weight;
class ProfileSetup extends StatelessWidget {
const ProfileSetup({super.key});
@override
Widget build(BuildContext context) {
var goal1 = false;
var goal2 = false;
var goal3 = false;
final controller =
PageController(viewportFraction: 0.8, keepPage: true, initialPage: 0);
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
40.h,
SmoothPageIndicator(
controller: controller, // PageController
count: 3,
effect: WormEffect(
dotHeight: 10,
dotWidth: 92,
dotColor: Colors.white,
activeDotColor:
HexColor("F2C70D")), // your preferred effect
),
32.h,
Text('What\'s your goal?',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
48.h,
GestureDetector(
onTap: () {
_goal = 'Lose Weight';
goal1 = true;
goal2 = false;
goal3 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: goal1 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Lose Weight',
style: TextStyle(
color: goal1 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
],
),
),
),
),
32.h,
GestureDetector(
onTap: () {
_goal = 'Gain Weight';
goal2 = true;
goal1 = false;
goal3 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: goal2 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Gain Weight',
style: TextStyle(
color: goal2 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
8.w,
],
),
),
),
),
32.h,
GestureDetector(
onTap: () {
_goal = 'Maintain Weight';
goal3 = true;
goal2 = false;
goal1 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: goal3 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Maintain Weight',
style: TextStyle(
color: goal3 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
8.w,
],
),
),
),
),
48.h,
TextButton(
onPressed: () {
navigateTo(context, ProfileSetup2());
},
style: ButtonStyle(
minimumSize:
const MaterialStatePropertyAll(Size(320, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
child: const Text('Next',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
),
],
),
),
);
},
);
}
}
class ProfileSetup2 extends StatelessWidget {
const ProfileSetup2({super.key});
@override
Widget build(BuildContext context) {
var diet1 = false;
var diet2 = false;
var diet3 = false;
var diet4 = false;
var controller = PageController(viewportFraction: 0.8, keepPage: true, initialPage: 1);
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
40.h,
SmoothPageIndicator(
controller: controller, // PageController
count: 3,
effect: WormEffect(
dotHeight: 10,
dotWidth: 92,
dotColor: Colors.white,
activeDotColor:
HexColor("F2C70D")), // your preferred effect
onDotClicked: (index) {}),
32.h,
Text('What\'s your preferred diet?',
textAlign: TextAlign.center,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
48.h,
GestureDetector(
onTap: () {
_diet = 'None';
diet1 = true;
diet2 = false;
diet3 = false;
diet4 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: diet1 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('None',
style: TextStyle(
color: diet1 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
],
),
),
),
),
32.h,
GestureDetector(
onTap: () {
_diet = 'Ketogenic';
diet1 = false;
diet2 = true;
diet3 = false;
diet4 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: diet2 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Ketogenic',
style: TextStyle(
color: diet2 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
],
),
),
),
),
32.h,
GestureDetector(
onTap: () {
_diet = 'Paleo';
diet1 = false;
diet2 = false;
diet3 = true;
diet4 = false;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: diet3 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Paleo',
style: TextStyle(
color: diet3 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
],
),
),
),
),
32.h,
GestureDetector(
onTap: () {
_diet = 'Vegan';
diet1 = false;
diet2 = false;
diet3 = false;
diet4 = true;
AppCubit.get(context).emit(SuccessRegisterState());
},
child: styledCard(
color: diet4 ? HexColor('F2C70D') : Colors.white,
width: 320.0,
height: 80.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Align(
alignment: Alignment.center,
child: Text('Vegan',
style: TextStyle(
color: diet4 ? Colors.white : Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
),
],
),
),
),
),
48.h,
TextButton(
onPressed: () {
navigateTo(context, ProfileSetup3());
},
style: ButtonStyle(
minimumSize:
const MaterialStatePropertyAll(Size(320, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
child: const Text('Next',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
),
],
),
),
),
);
},
);
}
}
class ProfileSetup3 extends StatelessWidget {
const ProfileSetup3({super.key});
@override
Widget build(BuildContext context) {
var weightController = TextEditingController();
var heightController = TextEditingController();
// Step 1.
String dropdownValue = 'Female';
// Step 2.
DropdownButton<String>(
// Step 3.
value: dropdownValue,
// Step 4.
items: <String>['Female', 'Male']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text('Female',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
);
}).toList(),
// Step 5.
onChanged: (String? newValue) {
dropdownValue = newValue!;
AppCubit.get(context).emit(SuccessRegisterState());
},
);
var controller = PageController(viewportFraction: 0.8, keepPage: true, initialPage: 2);
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
40.h,
SmoothPageIndicator(
controller: controller, // PageController
count: 3,
effect: WormEffect(
dotHeight: 10,
dotWidth: 92,
dotColor: Colors.white,
activeDotColor:
HexColor("F2C70D")), // your preferred effect
onDotClicked: (index) {}),
32.h,
Text('What\'re your dimensions?',
textAlign: TextAlign.center,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
48.h,
styledCard(
color: Colors.white,
width: 320.0,
height: 262.0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const Align(
alignment: Alignment.topLeft,
child: Text('Profile',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 32,
)),
),
16.h,
Row(
children: [
const Text('Weight',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
SizedBox(
height: 40,
width: 40,
child: TextFormField(
controller: weightController,
maxLength: 3,
maxLines: 1,
decoration: InputDecoration(
counterText: '',
),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
),
)),
8.w,
Text(
'KG',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
),
),
],
),
8.h,
Row(
children: [
const Text('Height',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
SizedBox(
height: 40,
width: 40,
child: TextFormField(
controller: heightController,
maxLength: 3,
maxLines: 1,
decoration: InputDecoration(
counterText: '',
),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
),
)),
8.w,
Text(
'CM',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
),
),
],
),
8.h,
Row(
children: [
const Text('Gender',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 24,
)),
const Spacer(),
GestureDetector(
onTap: () {},
child: DropdownButton<String>(
// Step 3.
value: dropdownValue,
// Step 4.
items: <String>['Female', 'Male']
.map<DropdownMenuItem<String>>(
(String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600,
fontSize: 18,
)),
);
}).toList(),
// Step 5.
onChanged: (String? newValue) {
dropdownValue = newValue!;
AppCubit.get(context)
.emit(SuccessRegisterState());
},
),
),
],
),
8.h,
],
),
),
),
48.h,
TextButton(
onPressed: () {
_height = heightController.text;
_weight = weightController.text;
_gender = dropdownValue;
AppCubit.get(context).setupProfile(
height: _height,
weight: _weight,
gender: _gender,
goal: _goal,
diet: _diet,
context: context,
);
},
style: ButtonStyle(
minimumSize:
const MaterialStatePropertyAll(Size(320, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
child: const Text('Next',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
),
],
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/BNB/bottomNav.dart
|
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/Components/components.dart';
import '../Exercises/exercises.dart';
import '../Home/home.dart';
import '../Meals/meals.dart';
class BNB extends StatelessWidget {
BNB({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {},
builder: (context, state) {
return Scaffold(
body: Stack(
children: [
AppCubit.get(context).currentScreen,
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Align(
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (AppCubit.get(context).currentScreen is HomeScreen)
styledCard(
height: 90.0,
width: 155.0,
color: HexColor('F2C70D'),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
PhosphorIcon(
PhosphorIconsFill.house,
size: 35,
color: Colors.white,
),
8.w,
Text('Home',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w500,
)),
],
),
),
if (AppCubit.get(context).currentScreen is! HomeScreen)
GestureDetector(
onTap: () {
AppCubit.get(context).changeBNB(HomeScreen());
},
child: styledCard(
height: 75.0,
width: 75.0,
color: Colors.white,
child: PhosphorIcon(
PhosphorIconsFill.house,
size: 35,
color: Colors.black,
),
),
),
16.w,
if (AppCubit.get(context).currentScreen is MealsScreen)
styledCard(
height: 90.0,
width: 155.0,
color: HexColor('F2C70D'),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
PhosphorIcon(
PhosphorIconsFill.bowlFood,
size: 35,
color: Colors.white,
),
8.w,
Text('Meals',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w500,
)),
],
),
),
if (AppCubit.get(context).currentScreen is! MealsScreen)
GestureDetector(
onTap: () {
AppCubit.get(context).changeBNB(MealsScreen());
},
child: styledCard(
height: 75.0,
width: 75.0,
color: Colors.white,
child: PhosphorIcon(
PhosphorIconsFill.bowlFood,
size: 35,
color: Colors.black,
),
),
),
16.w,
if (AppCubit.get(context).currentScreen
is ExercisesScreen)
styledCard(
height: 90.0,
width: 155.0,
color: HexColor('F2C70D'),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
PhosphorIcon(
PhosphorIconsFill.barbell,
size: 35,
color: Colors.white,
),
8.w,
Text('Exercises',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500,
)),
],
),
),
if (AppCubit.get(context).currentScreen
is! ExercisesScreen)
GestureDetector(
onTap: () {
AppCubit.get(context).changeBNB(ExercisesScreen());
},
child: styledCard(
height: 75.0,
width: 75.0,
color: Colors.white,
child: PhosphorIcon(
PhosphorIconsFill.barbell,
size: 35,
color: Colors.black,
),
),
),
],
),
),
),
],
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Start Exercise/startExercise.dart
|
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_timer_countdown/flutter_timer_countdown.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import '../../Shared/cubit/app_cubit.dart';
import '../BNB/bottomNav.dart';
class StartExercise extends StatelessWidget {
const StartExercise({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(listener: (context, state) {
// TODO: implement listener
}, builder: (context, state) {
final stopWatchTimer = StopWatchTimer(mode: StopWatchMode.countUp);
stopWatchTimer.onStartTimer();
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
body: Column(children: [
32.h,
Align(
alignment: Alignment.center,
child: styledCard(
color: Colors.white,
height: 680.0,
width: 320.0,
child: Column(children: [
20.h,
Align(
alignment: Alignment.topCenter,
child: PhosphorIcon(
PhosphorIconsFill.personSimpleRun,
size: 150,
color: Colors.black,
),
),
8.h,
Text('Running',
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
)),
24.h,
StreamBuilder<int>(
stream: stopWatchTimer.rawTime,
initialData: 0,
builder: (context, snap) {
final value = snap.data;
final displayTime =
StopWatchTimer.getDisplayTime(value!);
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
displayTime.toString().substring(0, 8),
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
),
),
),
24.h,
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0),
child: Row(
children: [
Text('Calories Burned:',
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
5.w,
Text(
StopWatchTimer.getDisplayTimeMinute(
value),
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.w500,
)),
],
),
),
),
],
);
},
),
// Text('0h:5m:45s',
// style: TextStyle(
// color: Colors.black,
// fontSize: 32,
// fontWeight: FontWeight.w600,
// )),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Tips',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
Text('• Maintain an upright posture',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text(
'• Run on soft surface to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
Text(
'• Take short strides to reduce joint impact',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
),
),
24.h,
TextButton(
onPressed: () {
navigateToAndFinish(context, BNB());
},
child: Text('Finish',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
minimumSize:
MaterialStatePropertyAll(Size(280, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
),
])))
]));
});
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/Home/home.dart
|
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../Shared/Components/components.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../Settings/settings.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: HexColor("E2E2E2"),
appBar: AppBar(
backgroundColor: HexColor("E2E2E2"),
centerTitle: true,
title: const Text('November 19th'),
actions: [
settingsIcon(),
],
),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: styledCard(
width: 360.0,
height: 235.0,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: styledCard(
offset: 3.0,
color: HexColor('2DD95D'),
height: 15.0,
width: 20.0),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"""564 Calories
Burned!""",
style: TextStyle(
fontSize: 32,
color: HexColor('2E2E2E'),
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'+15% more than yesterday',
style: TextStyle(
fontSize: 14,
color: HexColor('33CC34'),
fontWeight: FontWeight.w500,
),
),
24.h,
Container(
width: 320,
height: 15,
padding: const EdgeInsets.only(right: 39),
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
color: Colors.black,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
child: Stack(
children: [
Container(
width: 200,
height: 15,
clipBehavior: Clip.antiAlias,
decoration: ShapeDecoration(
color: const Color(0xFFF2C70D),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
],
),
),
8.h,
const Align(
alignment: Alignment.center,
child: Text(
'94% of daily goal reached',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF4E4E4E),
fontSize: 14,
fontWeight: FontWeight.w400,
),
),
)
],
)
],
),
),
),
),
24.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
children: [
Expanded(
child: styledCard(
height: 167.0,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: styledCard(
offset: 3.0,
color: HexColor('2DD95D'),
height: 15.0,
width: 20.0),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Sleep",
style: TextStyle(
fontSize: 18,
color: HexColor('2E2E2E'),
fontWeight: FontWeight.w600,
),
),
Text(
"8h 28m",
style: TextStyle(
fontSize: 24,
color: HexColor('4E4E4E'),
fontWeight: FontWeight.w500,
),
),
const Spacer(),
const Align(
alignment: Alignment.topRight,
child: PhosphorIcon(
PhosphorIconsFill.moon,
size: 48,
color: Colors.black,
),
),
],
)
],
),
)),
),
16.w,
Expanded(
child: styledCard(
height: 167.0,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: styledCard(
offset: 3.0,
color: HexColor('2DD95D'),
height: 15.0,
width: 20.0),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Activity",
style: TextStyle(
fontSize: 18,
color: HexColor('2E2E2E'),
fontWeight: FontWeight.w600,
),
),
Text(
"1h 28m",
style: TextStyle(
fontSize: 24,
color: HexColor('4E4E4E'),
fontWeight: FontWeight.w500,
),
),
const Spacer(),
const Align(
alignment: Alignment.topRight,
child: PhosphorIcon(
PhosphorIconsFill.lightning,
size: 48,
color: Colors.black,
),
),
],
)
],
),
)),
),
],
),
),
41.h,
const Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'Activities',
style: TextStyle(
color: Color(0xFF2E2E2E),
fontSize: 32,
fontWeight: FontWeight.w600,
),
)),
),
8.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
const Padding(
padding: EdgeInsets.only(top: 17.0, right: 16),
child: Align(
alignment: Alignment.topRight,
child: PhosphorIcon(
PhosphorIconsFill.personSimpleRun,
size: 36,
color: Colors.black,
),
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.sunHorizon,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Early Morning',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'Running',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
const Text(
'5 km',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
3.w,
const PhosphorIcon(
PhosphorIconsFill.fire,
size: 15,
color: Color(0xFF6E6E6E),
),
8.w,
const Text(
'513 kcal Burned',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
],
)
],
),
8.h,
],
)
],
)),
),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
const Padding(
padding: EdgeInsets.only(top: 17.0, right: 16),
child: Align(
alignment: Alignment.topRight,
child: PhosphorIcon(
PhosphorIconsFill.bicycle,
size: 36,
color: Colors.black,
),
),
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.sun,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Noon',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'Cycling',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
const Text(
'2 km',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
3.w,
const PhosphorIcon(
PhosphorIconsFill.fire,
size: 15,
color: Color(0xFF6E6E6E),
),
8.w,
const Text(
'273 kcal Burned',
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
],
)
],
),
8.h,
],
)
],
)),
),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.clockAfternoon,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Afternoon',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'No Activity',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
),
),
8.h,
],
),
8.h,
],
)
],
)),
),
16.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: styledCard(
width: 320.0,
height: 140.0,
color: Colors.white,
child: Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
20.w,
const Align(
alignment: Alignment.centerLeft,
child: PhosphorIcon(
PhosphorIconsFill.moon,
size: 100,
color: Colors.black,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Night',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
8.h,
Text(
'No Activity',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
fontWeight: FontWeight.w500,
),
),
8.h,
],
),
8.h,
],
)
],
)),
),
150.h,
],
),
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/ExerciseDetails/exerciseDetails.dart
|
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../Start Exercise/startExercise.dart';
class ExerciseDetails extends StatelessWidget {
const ExerciseDetails(
{super.key,
required this.name,
required this.equipment,
required this.focus,
required this.tips,
required this.image});
final name;
final equipment;
final focus;
final tips;
final image;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
appBar: AppBar(
elevation: 0,
backgroundColor: HexColor("E2E2E2"),
),
body: SingleChildScrollView(
child: Center(
child: Column(
children: [
styledCard(
height: 255.0,
width: 320.0,
color: Colors.white,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.network(
image,
fit: BoxFit.fill,
),
),
),
24.h,
Text(name,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
32.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 60.0),
child: Row(
children: [
Column(
children: [
Text('Focus Area',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 16,
fontWeight: FontWeight.w600,
)),
8.h,
Text(focus,
style: TextStyle(
color: HexColor('6E6E6E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
Spacer(),
Column(
children: [
Text(equipment,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 16,
fontWeight: FontWeight.w600,
)),
8.h,
Text('Bodyweight',
style: TextStyle(
color: HexColor('6E6E6E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
],
),
],
),
),
48.h,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Tips',
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 18,
fontWeight: FontWeight.w600,
)),
8.h,
SizedBox(
height: tips.length * 40.0,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: tips.length,
itemBuilder: (context, index) => Text(tips[index],
style: TextStyle(
color: HexColor('4E4E4E'),
fontSize: 14,
fontWeight: FontWeight.w500,
)),
),
),
32.h,
TextButton(
onPressed: () {
navigateTo(context, StartExercise());
},
child: Text('Start',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
minimumSize:
MaterialStatePropertyAll(Size(320, 47)),
backgroundColor:
MaterialStatePropertyAll(HexColor('F2C70D'))),
),
50.h,
],
),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules
|
mirrored_repositories/fitness_app/lib/Modules/SwapMeals/swapMeals.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fitness_app/Shared/Components/components.dart';
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
class SwapMealsScreen extends StatelessWidget {
const SwapMealsScreen({super.key});
@override
Widget build(BuildContext context) {
CollectionReference mealsCollection =
FirebaseFirestore.instance.collection('meals');
dynamic mealsRef = mealsCollection;
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
title: Text('Meals'),
actions: [
Padding(
padding: const EdgeInsets.all(20.0),
child: GestureDetector(
onTap: () {},
child: PhosphorIcon(
PhosphorIconsBold.magnifyingGlass,
size: 24,
color: Colors.black,
),
),
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
40.h,
StreamBuilder<QuerySnapshot>(
stream: mealsRef.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
final QuerySnapshot? querySnapshot = snapshot.data;
if (querySnapshot == null) {
print('DATA DOES NOT EXIST.');
return Text(
'No data available',
);
}
return ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) {
final DocumentSnapshot<Object?> document =
querySnapshot.docs[index];
return mealWidget(
name: document['name'],
calories: document['calories'],
diet: document['diet'],
time: document['time'],
image: document['image']);
},
separatorBuilder: (context, index) => 16.h,
itemCount: querySnapshot.docs.length,
physics: NeverScrollableScrollPhysics(),
);
},
),
40.h,
],
),
),
);
},
);
}
}
class mealWidget extends StatelessWidget {
const mealWidget({
super.key,
required this.name,
required this.image,
required this.time,
required this.diet,
required this.calories,
});
final name;
final image;
final time;
final diet;
final calories;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: styledCard(
width: 320.0,
height: 174.0,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Stack(
children: [
Row(
children: [
Align(
alignment: Alignment.centerLeft,
child: SizedBox(
height: 100,
width: 100,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Image.network(
image,
fit: BoxFit.fill,
),
),
),
),
20.w,
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
maxLines: 1,
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 24,
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w500,
),
),
8.h,
Row(
children: [
Text(
time,
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
8.w,
PhosphorIcon(
PhosphorIconsFill.dot,
size: 15,
color: Color(0xFF6E6E6E),
),
8.w,
Text(
"$calories kcal",
style: TextStyle(
color: Color(0xFF6E6E6E),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
],
),
16.h,
TextButton(
onPressed: () {},
child: Text('Swap',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
)),
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
HexColor('F2C70D'))),
)
],
),
),
8.h,
],
)
],
),
)),
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules/Authentication
|
mirrored_repositories/fitness_app/lib/Modules/Authentication/Sign Up/signup.dart
|
import 'package:fitness_app/Modules/Authentication/Login/login.dart';
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../../Shared/Components/components.dart';
import '../../BNB/bottomNav.dart';
var emailController = TextEditingController();
var passwordController = TextEditingController();
var formKey = GlobalKey<FormState>();
Widget suffixWidgetPassword = const Icon(
Icons.visibility,
color: Colors.white,
);
bool fieldStatus = true;
Widget? suffixWidgetEmail = null;
var usernameController = TextEditingController();
var confirmPasswordController = TextEditingController();
class SignUpScreen extends StatelessWidget {
const SignUpScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
if (state is SuccessRegisterState) {
navigateToAndFinish(context, BNB());
}
},
builder: (context, state) {
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
body: Center(
child: SingleChildScrollView(
child: Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Welcome',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
32.h,
TextFormField(
controller: usernameController,
validator: (value) {
if (value!.isEmpty) {
return 'Username cannot be left empty.';
}
return null;
},
decoration: InputDecoration(
hintText: 'Username',
prefixIcon: const Icon(
Icons.person,
color: Colors.white,
),
filled: true,
fillColor: Colors.white.withOpacity(0.3),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
),
),
20.h,
TextFormField(
validator: (value) {
if (value!.isEmpty) {
return 'E-mail cannot be left empty.';
} else if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
keyboardType: TextInputType.emailAddress,
controller: emailController,
decoration: InputDecoration(
hintText: 'Email',
prefixIcon: const Icon(
Icons.email,
color: Colors.white,
),
filled: true,
fillColor: Colors.white.withOpacity(0.3),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
),
),
20.h,
TextFormField(
controller: passwordController,
validator: (value) {
if (value!.isEmpty) {
return 'Password cannot be left empty.';
}
return null;
},
obscureText: AppCubit.get(context).isViewable,
decoration: InputDecoration(
hintText: 'Create Password',
prefixIcon: const Icon(
Icons.lock,
color: Colors.white,
),
suffixIcon: InkWell(
onTap: () {
AppCubit.get(context).changeViewable();
},
child: const Icon(
Icons.visibility,
color: Colors.white,
),
),
filled: true,
fillColor: Colors.white.withOpacity(0.3),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
),
),
20.h,
TextFormField(
controller: confirmPasswordController,
validator: (value) {
if (value!.isEmpty) {
return 'Field cannnot be left empty.';
}
if (value.toString() != passwordController.text) {
return 'Please recheck your password before proceeding.';
}
return null;
},
obscureText: AppCubit.get(context).isViewable,
decoration: InputDecoration(
hintText: 'Confirm Password',
prefixIcon: const Icon(
Icons.lock,
color: Colors.white,
),
suffixIcon: InkWell(
onTap: () {
AppCubit.get(context).changeViewable();
},
child: const Icon(
Icons.visibility,
color: Colors.white,
),
),
filled: true,
fillColor: Colors.white.withOpacity(0.3),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
),
),
24.h,
GestureDetector(
onTap: () {
if (formKey.currentState!.validate()) {
AppCubit.get(context).register(
email: emailController.text,
password: passwordController.text,
context: context,
name: usernameController.text);
}
},
child: styledCard(
height: 68.0,
color: Colors.white,
width: 320.0,
child: Center(
child: Text('Sign Up',
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
),
),
24.h,
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Already have an account?',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
8.w,
GestureDetector(
onTap: () {
navigateTo(context, LoginScreen());
},
child: Text(
'Login',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
decoration: TextDecoration.underline),
),
),
],
),
],
),
),
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules/Authentication
|
mirrored_repositories/fitness_app/lib/Modules/Authentication/Welcome/welcome.dart
|
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../../Shared/Components/components.dart';
import '../Login/login.dart';
import '../Sign Up/signup.dart';
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
// TODO: implement listener
},
builder: (context, state) {
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Welcome',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
32.h,
GestureDetector(
onTap: () {
navigateTo(context, SignUpScreen());
},
child: styledCard(
height: 68.0,
color: HexColor('F2C70D'),
width: 320.0,
child: Center(
child: Text('Sign Up',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
),
),
24.h,
GestureDetector(
onTap: () {
navigateTo(context, LoginScreen());
},
child: styledCard(
height: 68.0,
color: Colors.white,
width: 320.0,
child: Center(
child: Text('Login',
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
),
)
],
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Modules/Authentication
|
mirrored_repositories/fitness_app/lib/Modules/Authentication/Login/login.dart
|
import 'package:fitness_app/Modules/BNB/bottomNav.dart';
import 'package:fitness_app/Shared/cubit/app_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:speed_up_flutter/speed_up_flutter.dart';
import '../../../Shared/Components/components.dart';
import '../../AdminPanel/admin.dart';
import '../Sign Up/signup.dart';
class LoginScreen extends StatelessWidget {
LoginScreen({super.key});
var emailController = TextEditingController();
var passwordController = TextEditingController();
var formKey = GlobalKey<FormState>();
Widget suffixWidgetPassword = const Icon(
Icons.visibility,
color: Colors.white,
);
bool fieldStatus = true;
Widget? suffixWidgetEmail = null;
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppState>(
listener: (context, state) {
if (state is LoadingLoginState) {
fieldStatus = false;
suffixWidgetEmail = const CircularProgressIndicator(
color: Colors.white38,
strokeWidth: 1,
);
suffixWidgetPassword = const CircularProgressIndicator(
color: Colors.white38,
strokeWidth: 1,
);
} else {
fieldStatus = true;
suffixWidgetEmail = null;
suffixWidgetPassword = const Icon(
Icons.visibility,
color: Colors.white,
);
}
if (state is SuccessLoginState) {
navigateToAndFinish(context, BNB());
}
},
builder: (context, state) {
return Scaffold(
backgroundColor: HexColor('E2E2E2'),
body: Form(
key: formKey,
child: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Welcome Back',
style: TextStyle(
color: HexColor('2E2E2E'),
fontSize: 32,
fontWeight: FontWeight.w600,
)),
32.h,
TextFormField(
controller: emailController,
validator: (value) {
if (value!.isEmpty) {
return 'E-mail cannot be left empty.';
} else if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
decoration: const InputDecoration(
errorStyle: TextStyle(
color: Color.fromARGB(255, 255, 100, 89),
),
labelText: 'Email',
labelStyle: TextStyle(color: Colors.white),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
),
),
20.h,
TextFormField(
controller: passwordController,
validator: (value) {
if (value!.isEmpty) {
return 'Password cannot be left empty.';
}
return null;
},
decoration: InputDecoration(
errorStyle: const TextStyle(
color: Color.fromARGB(255, 255, 100, 89),
),
suffixIcon: InkWell(
onTap: () {
AppCubit.get(context).changeViewable();
},
child: suffixWidgetPassword,
),
labelText: 'Password',
labelStyle: const TextStyle(color: Colors.white),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
),
obscureText: AppCubit.get(context).isViewable,
),
24.h,
GestureDetector(
onLongPress: () {
navigateToAndFinish(context, BNB());
},
onTap: () {
if (emailController.text == 'admin' &&
passwordController.text == 'admin') {
navigateToAndFinish(context, AdminPanel());
}
if (formKey.currentState!.validate()) {
AppCubit.get(context)
.loginUser(emailController.text,
passwordController.text, context)
.then((value) {});
}
},
child: styledCard(
height: 68.0,
color: Colors.white,
width: 320.0,
child: Center(
child: Text('Login',
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontWeight: FontWeight.w600,
)),
),
),
),
24.h,
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Forgot password?',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
8.w,
GestureDetector(
onTap: () {},
child: Text(
'Reset password',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
decoration: TextDecoration.underline),
),
),
],
),
16.h,
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Don\'t have an account?',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
8.w,
GestureDetector(
onTap: () {
navigateToAndFinish(context, SignUpScreen());
},
child: Text(
'Sign up',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
decoration: TextDecoration.underline),
),
),
],
),
],
),
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Shared
|
mirrored_repositories/fitness_app/lib/Shared/Constants/constants.dart
|
import '../../Network/local/cacheHelper.dart';
var uid = CacheHelper.getData(key: 'uid');
var metricUnits = CacheHelper.getData(key: 'metricUnits');
| 0
|
mirrored_repositories/fitness_app/lib/Shared
|
mirrored_repositories/fitness_app/lib/Shared/Components/components.dart
|
import 'package:flutter/material.dart';
import '../../Modules/Settings/settings.dart';
class styledCard extends StatelessWidget {
styledCard({
super.key,
this.width,
this.height,
this.color,
this.child,
this.offset = 9.0,
});
final width;
final height;
final color;
final child;
var offset;
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: color,
border: Border.all(width: 4),
boxShadow: [
BoxShadow(
color: Color(0xFF000000),
blurRadius: 0,
offset: Offset(offset, offset),
spreadRadius: 0,
)
],
),
child: child,
);
}
}
Future<void> navigateToAndFinish(context, widget) async =>
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => widget),
(route) => false,
);
Future<void> navigateTo(context, widget) async => Navigator.push(
context,
MaterialPageRoute(builder: (context) => widget),
);
class settingsIcon extends StatelessWidget {
const settingsIcon({
super.key,
});
@override
Widget build(BuildContext context) {
return IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
navigateTo(context, SettingsScreen());
},
);
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Shared
|
mirrored_repositories/fitness_app/lib/Shared/cubit/app_cubit.dart
|
import 'package:bloc/bloc.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:fitness_app/Modules/Home/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import '../../Modules/Authentication/Welcome/welcome.dart';
import '../../Modules/Exercises/exercises.dart';
import '../../Modules/Meals/meals.dart';
import '../../Modules/ProfileSetup/profileSetup.dart';
import '../../Network/local/cacheHelper.dart';
import '../../main.dart';
import '../Components/components.dart';
import '../Constants/constants.dart';
part 'app_state.dart';
class AppCubit extends Cubit<AppState> {
AppCubit() : super(AppInitial());
static AppCubit get(context) => BlocProvider.of(context);
List<Widget> screens = [
const HomeScreen(),
const MealsScreen(),
const ExercisesScreen()
];
dynamic currentScreen = const HomeScreen();
void changeBNB(screen) {
currentScreen = screen;
emit(BNBChangeState());
}
bool isViewable = true;
void changeViewable() {
if (isViewable == true) {
isViewable = false;
} else if (isViewable == false) {
isViewable = true;
}
print(isViewable);
emit(SuffixChangeState());
}
Future<Object?> register(
{required String email,
required String password,
required context,
required String name}) async {
final FirebaseAuth _auth = FirebaseAuth.instance;
try {
emit(LoadingRegisterState());
UserCredential userCredential = await _auth
.createUserWithEmailAndPassword(
email: email,
password: password,
)
.then((value) async {
print(value.user?.uid);
// CREATION OF USER-------------
FirebaseFirestore.instance
.collection('users')
.doc(value.user?.uid)
.set({
'name': name,
'email': email,
'uid': value.user?.uid,
});
await CacheHelper.saveData(key: 'uid', value: value.user?.uid);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text("Account created successfully!",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
navigateToAndFinish(context, const ProfileSetup());
return value;
});
return userCredential;
} on FirebaseAuthException catch (e) {
emit(ErrorRegisterState());
if (e.code == 'weak-password') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content: Text("The password provided is too weak.",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content: Text("The account already exists for that email.",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
}
return e.message;
} catch (e) {
return e.toString();
}
}
Future<UserCredential?> loginUser(
String email,
String password,
context,
) async {
FirebaseAuth auth = FirebaseAuth.instance;
try {
emit(LoadingLoginState());
UserCredential userCredential = await auth
.signInWithEmailAndPassword(email: email, password: password)
.then((value) async {
print(value.user?.uid);
await CacheHelper.saveData(key: 'uid', value: value.user?.uid);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content:
Text("Login Success!", style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
emit(SuccessLoginState());
return value;
});
return userCredential;
} on FirebaseAuthException catch (e) {
emit(ErrorLoginState());
if (e.code == 'user-not-found') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content:
Text("User not found.", style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content: Text("Wrong password provided for that user.",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
}
return null;
}
}
Future<void> logout(context) async {
await CacheHelper.removeData(key: 'uid');
navigateToAndFinish(context, const WelcomeScreen());
}
void addExercise(
{required name,
required focusArea,
required equipment,
required List<String> tips,
required image,
required context}) {
FirebaseFirestore.instance.collection('exercises').doc().set({
'name': name,
'icon': '',
'image': image,
'focus area': focusArea,
'equipment': equipment,
'tips': tips,
}).then((value) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text("Exercise added successfully!",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
}).catchError((e) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content: Text("Failed to add exercise.",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
});
}
void addMeal({
required diet,
required image,
required name,
required time,
required calories,
required List<String> ingredients,
required List<String> instructions,
required context,
}) {
FirebaseFirestore.instance.collection('meals').doc().set({
'diet': diet,
'image': image,
'name': name,
'time': time,
'calories': calories,
'ingredients': ingredients,
'instructions': instructions,
}).then((value) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text("Meal added successfully!",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
}).catchError((e) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.red,
content:
Text("Failed to add meal.", style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
});
}
Future<List<DocumentSnapshot>> searchDocuments(String searchQuery) async {
emit(SearchLoadingState());
final QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('exercises') // Replace with your collection name
.where('name', isGreaterThanOrEqualTo: searchQuery)
.get()
.whenComplete(() {
emit(SearchSuccessState());
}).catchError((e) {
emit(SearchErrorState());
print(e.toString());
});
return snapshot.docs;
}
String searchQuery = '';
List<DocumentSnapshot> searchResults = [];
void performSearch() async {
emit(StartSearchState());
if (searchQuery.isNotEmpty) {
final List<DocumentSnapshot> results =
await searchDocuments(searchQuery.toUpperCase());
searchResults = results;
}
}
void setupProfile({
required height,
required weight,
required gender,
required goal,
required diet,
required context,
}) {
FirebaseFirestore.instance.collection('users').doc(uid).update({
'height': height,
'weight': weight,
'gender': gender,
'goal': goal,
'diet': diet,
}).then((value) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text("Profile set successfully!",
style: TextStyle(color: Colors.white)),
duration: Duration(seconds: 3),
));
navigateToAndFinish(context, home);
});
}
var height;
var weight;
var goal;
var diet;
var gender;
var weightUnit;
var lenghtUnit;
Future<void> getUserProfile() async {
if (await CacheHelper.getData(key: 'metricUnits') == null) {
metricUnits = true;
}
if (metricUnits == true) {
weightUnit = 'KG';
lenghtUnit = 'CM';
} else if (metricUnits == false) {
weightUnit = 'IB';
lenghtUnit = 'FT';
}
var collection = FirebaseFirestore.instance.collection('users');
var docSnapshot = await collection.doc(uid).get();
if (docSnapshot.exists) {
Map<String, dynamic> data = docSnapshot.data()!;
print('USER PROFILE FOUND');
height = data['height'];
weight = data['weight'];
goal = data['goal'];
diet = data['diet'];
gender = data['gender'];
}
}
Future<void> changeUnit(val) async {
await CacheHelper.saveData(key: 'metricUnits', value: val);
metricUnits = await CacheHelper.getData(key: 'metricUnits');
if (metricUnits == true) {
weightUnit = 'KG';
lenghtUnit = 'CM';
} else if (metricUnits == false) {
weightUnit = 'IB';
lenghtUnit = 'FT';
}
emit(ChangeUnitState());
}
}
| 0
|
mirrored_repositories/fitness_app/lib/Shared
|
mirrored_repositories/fitness_app/lib/Shared/cubit/app_state.dart
|
part of 'app_cubit.dart';
@immutable
sealed class AppState {}
final class AppInitial extends AppState {}
final class BNBChangeState extends AppState {}
final class SuffixChangeState extends AppState {}
// LOGIN STATES
class LoadingLoginState extends AppState {}
class ErrorLoginState extends AppState {}
class SuccessLoginState extends AppState {}
// REGISTER STATES
class LoadingRegisterState extends AppState {}
class ErrorRegisterState extends AppState {}
class SuccessRegisterState extends AppState {}
// Search states
final class StartSearchState extends AppState {}
final class SearchLoadingState extends AppState {}
final class SearchSuccessState extends AppState {}
final class SearchErrorState extends AppState {}
// Set Profile States
final class SetProfileState extends AppState {}
final class ChangeUnitState extends AppState {}
| 0
|
mirrored_repositories/fitness_app
|
mirrored_repositories/fitness_app/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 in the flutter_test package. 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:fitness_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const 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/Flutter-Apple-Store
|
mirrored_repositories/Flutter-Apple-Store/lib/main.dart
|
import 'package:catalog/Screens/SplashScreen.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences pref = await SharedPreferences.getInstance();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
.then((value) => runApp(ChangeNotifierProvider(
create: (context) => CartModel(),
child: GetMaterialApp(
builder: (context, child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: child!);
},
debugShowCheckedModeBanner: false,
theme: ThemeData(fontFamily: 'SF'),
title: 'Apple Store',
color: Colors.white,
home: SplashScreen(
pref: pref,
),
),
)));
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Products/apple_watches.dart
|
import 'package:badges/badges.dart';
import 'package:catalog/Helper/ItemContainer.dart';
import 'package:catalog/Screens/cart.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
class Watches extends StatefulWidget {
const Watches({Key? key}) : super(key: key);
@override
_WatchesState createState() => _WatchesState();
}
class _WatchesState extends State<Watches> {
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.black,
size: 22,
),
onPressed: () {
Navigator.pop(context);
}),
actions: [
IconButton(
icon: Badge(
badgeContent: cart.listlength != 0
? Text("${cart.listlength}")
: Text(''),
badgeColor: Colors.amber,
child: Icon(
Icons.shopping_cart_outlined,
color: Colors.black,
size: 22,
),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (c) => Cart()));
})
],
centerTitle: true,
backgroundColor: Colors.white,
title: Text(
"Watch",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
),
body: Stack(children: [
Positioned(
child: Text(
"Featured Watches",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
top: 10,
left: 20,
),
buildgrid(),
]),
);
}
}
Widget buildgrid() {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
childAspectRatio: 0.87,
children: <Widget>[
ItemContainer(
itemId: 4,
height: 135,
tag: "1",
name: 'Apple watch S6+',
price: 399,
imagename: 'watches/watchs6+',
),
ItemContainer(
itemId: 4,
height: 135,
tag: "2",
name: 'Apple watch S6',
price: 359,
imagename: 'watches/watchs6',
),
ItemContainer(
itemId: 4,
height: 135,
tag: "3",
name: 'Apple watch SE+',
price: 320,
imagename: 'watches/watchse+',
),
ItemContainer(
itemId: 4,
height: 135,
tag: "4",
name: 'Apple watch SE',
price: 279,
imagename: 'watches/watchse',
),
ItemContainer(
itemId: 4,
height: 135,
tag: "5",
name: 'Apple watch S5',
price: 249,
imagename: 'watches/iwatch',
),
ItemContainer(
itemId: 4,
height: 135,
tag: "6",
name: 'Apple watch S3',
price: 199,
imagename: 'watches/watch3',
),
],
),
);
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Products/mac.dart
|
import 'package:badges/badges.dart';
import 'package:catalog/Helper/ItemContainer.dart';
import 'package:catalog/Screens/cart.dart';
import 'package:flutter/material.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:provider/provider.dart';
class Mac extends StatefulWidget {
const Mac({Key? key}) : super(key: key);
@override
_MacState createState() => _MacState();
}
class _MacState extends State<Mac> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.black,
size: 22,
),
onPressed: () {
Navigator.pop(context);
}),
actions: [
IconButton(
icon: Badge(
badgeContent: cart.listlength != 0
? Text("${cart.listlength}")
: Text(''),
badgeColor: Colors.amber,
child: Icon(
Icons.shopping_cart_outlined,
color: Colors.black,
size: 22,
),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (c) => Cart()));
})
],
centerTitle: true,
backgroundColor: Colors.white,
title: Text(
"iMac",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
),
body: Stack(children: [
Positioned(
child: Text(
"Featured iPhones",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
top: 10,
left: 20,
),
buildgrid()
]),
);
}
}
Widget buildgrid() {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
childAspectRatio: 0.8,
children: <Widget>[
// ItemContainer(),
ItemContainer(
itemId: 2,
height: 135,
tag: "1",
name: 'MacBook Air',
price: 999,
imagename: 'macbook/macair',
),
ItemContainer(
itemId: 2,
height: 135,
tag: "2",
name: 'MacBook Pro M1"',
price: 1669,
imagename: 'macbook/macair',
),
ItemContainer(
itemId: 2,
height: 135,
tag: "3",
name: 'MacBook Pro 13"',
price: 1989,
imagename: 'macbook/macpro13',
),
ItemContainer(
itemId: 2,
height: 135,
tag: "4",
name: 'MacBook Pro 16"',
price: 2399,
imagename: 'macbook/macpro16',
),
ItemContainer(
itemId: 2,
height: 135,
tag: "5",
name: 'iMac 24"',
price: 1299,
imagename: 'macbook/imacF',
),
ItemContainer(
itemId: 2,
height: 135,
tag: "6",
name: 'iMac 27"',
price: 1589,
imagename: 'macbook/imacB',
),
],
),
);
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Products/airpods.dart
|
import 'package:badges/badges.dart';
import 'package:catalog/Helper/ItemContainer.dart';
import 'package:catalog/Screens/cart.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Airpods extends StatefulWidget {
const Airpods({Key? key}) : super(key: key);
@override
_AirpodsState createState() => _AirpodsState();
}
class _AirpodsState extends State<Airpods> {
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.black,
size: 22,
),
onPressed: () {
Navigator.pop(context);
}),
actions: [
IconButton(
icon: Badge(
badgeContent: cart.listlength != 0
? Text("${cart.listlength}")
: Text(''),
badgeColor: Colors.amber,
child: Icon(
Icons.shopping_cart_outlined,
color: Colors.black,
size: 22,
),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (c) => Cart()));
})
],
centerTitle: true,
backgroundColor: Colors.white,
title: Text(
"AirPods",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
),
body: Stack(children: [
Positioned(
child: Text(
"Featured AirPods",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
top: 10,
left: 20,
),
buildgrid(),
]),
);
}
}
Widget buildgrid() {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
childAspectRatio: 0.87,
children: <Widget>[
ItemContainer(
itemId: 5,
height: 135,
tag: "1",
name: 'AirPods Max',
price: 439,
imagename: 'airpods/airpodsmax',
),
ItemContainer(
itemId: 5,
height: 135,
tag: "2",
name: 'AirPods Pro',
price: 269,
imagename: 'airpods/airpodspro',
),
ItemContainer(
itemId: 5,
height: 135,
tag: "3",
name: 'AirPods WC',
price: 189,
imagename: 'airpods/airpods',
),
ItemContainer(
itemId: 5,
height: 135,
tag: "4",
name: 'AirPods',
price: 99,
imagename: 'airpods/airpods',
),
// ItemContainer(
// itemId: 4,
// height: 135,
// tag: "5",
// name: 'Apple watch S5',
// price: 1145,
// imagename: 'watches/iwatch',
// ),
// ItemContainer(
// itemId: 4,
// height: 135,
// tag: "6",
// name: 'Apple watch S3',
// price: 1145,
// imagename: 'watches/watch3',
// ),
],
),
);
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Products/iPad.dart
|
import 'package:badges/badges.dart';
import 'package:catalog/Helper/ItemContainer.dart';
import 'package:catalog/Screens/cart.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
class Ipad extends StatefulWidget {
const Ipad({Key? key}) : super(key: key);
@override
_IpadState createState() => _IpadState();
}
class _IpadState extends State<Ipad> {
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.black,
size: 22,
),
onPressed: () {
Navigator.pop(context);
}),
actions: [
IconButton(
icon: Badge(
badgeContent: cart.listlength != 0
? Text("${cart.listlength}")
: Text(''),
badgeColor: Colors.amber,
child: Icon(
Icons.shopping_cart_outlined,
color: Colors.black,
size: 22,
),
),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (c) => Cart()));
})
],
centerTitle: true,
backgroundColor: Colors.white,
title: Text(
"iPad",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
),
body: Stack(children: [
Positioned(
child: Text(
"Featured iPads",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
top: 10,
left: 20,
),
buildgrid(),
]),
);
}
}
Widget buildgrid() {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
childAspectRatio: 0.87,
children: <Widget>[
ItemContainer(
itemId: 3,
height: 135,
tag: "1",
name: 'iPad Pro 12.9"',
price: 799,
imagename: 'ipad/ipadpro',
),
ItemContainer(
itemId: 3,
height: 135,
tag: "2",
name: 'iPad Air 10.9"',
price: 599,
imagename: 'ipad/ipadair',
),
ItemContainer(
itemId: 3,
height: 135,
tag: "3",
name: 'iPad Pro 11""',
price: 329,
imagename: 'ipad/ipad11',
),
ItemContainer(
itemId: 3,
height: 135,
tag: "4",
name: 'iPad 10.2"',
price: 301,
imagename: 'ipad/ipad102',
),
ItemContainer(
itemId: 3,
height: 135,
tag: "5",
name: 'iPad Mini 7.9"',
price: 399,
imagename: 'ipad/ipad79',
),
// ItemContainer(
// itemId: 2,
// height: 135,
// tag: "6",
// name: 'iMac 27"',
// price: "\$ 1145",
// imagename: 'macbook/imacB',
// ),
],
),
);
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Products/iPhones.dart
|
import 'package:badges/badges.dart';
import 'package:catalog/Helper/ItemContainer.dart';
import 'package:catalog/Screens/cart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:provider/provider.dart';
class IPhones extends StatefulWidget {
const IPhones({Key? key}) : super(key: key);
@override
_IPhonesState createState() => _IPhonesState();
}
class _IPhonesState extends State<IPhones> {
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.black,
size: 22,
),
onPressed: () {
Navigator.pop(context);
}),
actions: [
IconButton(
icon: Badge(
badgeContent: cart.listlength != 0
? Text("${cart.listlength}")
: Text(''),
badgeColor: Colors.amber,
child: Icon(
Icons.shopping_cart_outlined,
color: Colors.black,
size: 22,
),
),
onPressed: () {
Get.to(() => Cart());
})
],
// centerTitle: true,
backgroundColor: Colors.white,
title: Text(
"iPhones",
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
),
body: Stack(
children: [
buildgrid(),
Positioned(
child: Text(
"Featured iPhones",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
top: 10,
left: 20,
),
],
),
);
}
}
Widget buildgrid() {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
childAspectRatio: 0.77,
children: <Widget>[
// ItemContainer(),
ItemContainer(
itemId: 1,
height: 160,
tag: "1",
name: 'iPhone X (RED)',
price: 499,
imagename: 'iPhones/iphoneX',
),
ItemContainer(
itemId: 1,
height: 160,
tag: "2",
name: 'iPhone 12 Pro',
price: 999,
imagename: 'iPhones/iphone12',
),
ItemContainer(
itemId: 1,
height: 160,
tag: "3",
name: 'iPhone X Max (GOLD)',
price: 659,
imagename: 'iPhones/iphoneXmax'),
ItemContainer(
itemId: 1,
height: 160,
tag: "4",
name: 'iPhone 11 (128GB)',
price: 759,
imagename: 'iPhones/iphone11',
),
ItemContainer(
itemId: 1,
height: 160,
tag: "5",
name: 'iPhone 11 (64GB)',
price: 699,
imagename: 'iPhones/iphone1164',
),
ItemContainer(
itemId: 1,
height: 160,
tag: "6",
name: 'iPhone 7',
price: 489,
imagename: 'iPhones/iphone7'),
],
),
);
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/profile.dart
|
import 'package:awesome_card/awesome_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'LoginScreen.dart';
class Profile extends StatefulWidget {
final pref;
const Profile({Key? key, required this.pref}) : super(key: key);
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
String bankname = 'Axis Bank';
bool showBack = false;
late SharedPreferences preferences;
void displayLogoutDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Alert"),
content: new Text("Are you sure you want to Logout."),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoDialogAction(
isDefaultAction: true,
child: new Text(
"Logout",
style: TextStyle(color: Colors.red),
),
onPressed: () {
print("Account Logged Out");
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (c) => LoginScreen(pref: widget.pref)));
},
)
],
),
);
}
void displayDeleteDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Alert"),
content: new Text(
"Are you sure you want to delete your account. Your email and password will be removed from database."),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoDialogAction(
isDefaultAction: false,
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
print("Account deleted");
widget.pref.remove('email');
widget.pref.remove('name');
widget.pref.remove('password');
widget.pref.remove('phone');
widget.pref.remove('cardholdername');
widget.pref.remove('cardno');
widget.pref.remove('cardexp');
widget.pref.remove('cvv');
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (c) => LoginScreen(pref: widget.pref)));
},
)
],
),
);
}
void menuAction(String value) {
switch (value) {
case 'Logout':
displayLogoutDialog();
break;
case 'Delete account':
displayDeleteDialog();
break;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(children: [
Align(
alignment: Alignment.topRight,
child: PopupMenuButton(
onSelected: menuAction,
itemBuilder: (BuildContext itemBuilder) =>
{'Logout', 'Delete account'}
.map((value) => PopupMenuItem(
child: Text(value),
value: value,
))
.toList())),
Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
child: Container(
height: 160,
width: 130,
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [Colors.white, Colors.lightBlueAccent],
radius: 0.6),
borderRadius: BorderRadius.circular(20.9)),
child: Image.asset(
'asset/images/profile.png',
),
),
),
SizedBox(height: 10),
Center(
child: Text(
'${widget.pref.getString('name')}',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
),
SizedBox(height: 5),
Center(
child: Text(
'+91 ${widget.pref.getString('phone')}',
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18),
),
),
SizedBox(height: 30),
Center(
child: GestureDetector(
onTap: () {
setState(() {
showBack = !showBack;
});
},
child: CreditCard(
cardNumber: widget.pref.getString('cardno'),
cardExpiry: widget.pref.getString('cardexp'),
cardHolderName: widget.pref.getString('cardholdername'),
cardType: CardType.masterCard,
cvv: widget.pref.getString('cvv'),
bankName: widget.pref.getString('bankname'),
showBackSide: showBack,
frontBackground: CardBackgrounds.black,
backBackground: CardBackgrounds.white,
showShadow: true,
),
),
)
]),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/cart.dart
|
import 'package:catalog/Helper/search.dart';
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
class Cart extends StatelessWidget {
const Cart({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var cart = context.watch<CartModel>();
return Scaffold(
body: cart.cartItems.length != 0
? SafeArea(
child: Stack(
children: [
Positioned(
top: 2,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Positioned(
top: 10,
right: 135,
child: Text(
"My Cart",
style: TextStyle(
fontSize: 28, fontWeight: FontWeight.bold),
)),
Positioned(
top: 50,
right: 155,
child: Text(
"${cart.cartItems.length} Items",
style: TextStyle(fontSize: 18, color: Colors.grey),
)),
Positioned(
bottom: 15,
left: 70,
child: MaterialButton(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
onPressed: () {
Fluttertoast.showToast(
msg:
"This is just a prototype. Thank you for showing the intrest.",
gravity: ToastGravity.BOTTOM);
},
child: Padding(
padding: const EdgeInsets.fromLTRB(40, 15, 40, 15),
child: Text(
"CHECKOUT",
style: TextStyle(fontSize: 22, color: Colors.white),
),
),
color: Color(0xff343434), //jet black color
)),
Positioned(
bottom: 85,
left: 30,
child: Row(
children: [
Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 15.0,
color: Colors.black87.withOpacity(0.05),
),
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.local_shipping_rounded),
Text(
"FREE",
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(width: 15),
Container(
height: 66,
width: 180,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
// color: const Color(0xFF000000),
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 15.0,
color: Colors.black87.withOpacity(0.05),
),
]),
child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Total :',
style: TextStyle(
fontSize: 14, color: Colors.grey)),
),
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
"\$ ${cart.totalPrice}",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold),
),
),
),
],
),
),
],
)),
Gridbuilder(cart: cart),
],
),
)
: SafeArea(
child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
alignment: Alignment.topLeft,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded)),
),
Text(
"My Cart",
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
Padding(
padding: const EdgeInsets.only(top: 30),
child: Image.asset(
'asset/images/add2cart.png',
height: 300,
width: 200,
),
),
Text(
"Your cart is empty!",
style: TextStyle(fontSize: 28),
),
Text(
'Add items to it now.',
style: TextStyle(fontSize: 16, color: Colors.grey),
),
SizedBox(height: 20),
MaterialButton(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
onPressed: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (c) => SerachBarPage()));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Shop now",
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
color: Colors.black,
)
],
),
),
);
}
}
class Gridbuilder extends StatelessWidget {
const Gridbuilder({
Key? key,
required this.cart,
}) : super(key: key);
final CartModel cart;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 80, bottom: 170),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
crossAxisSpacing: 10,
childAspectRatio: 2.3,
mainAxisSpacing: 10,
),
primary: false,
padding: const EdgeInsets.all(20),
itemCount: cart.listlength,
itemBuilder: (context, index) {
if (index >= cart.cartItems.length) {
return const Offstage();
}
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 15.0,
color: Colors.black87.withOpacity(0.05),
),
]),
child: Stack(
children: [
Positioned(
top: 15,
left: 10,
child: Container(
height: 100,
width: 130,
child: Image.asset(
'asset/images/${cart.cartItems[index].imagename}.png'),
),
),
Positioned(
top: 30,
left: 150,
child: Column(
children: [
Align(
alignment: Alignment.center,
child: Text(
"${cart.cartItems[index].name}",
style: TextStyle(fontSize: 18),
)),
SizedBox(height: 10),
Align(
alignment: Alignment.center,
child: Text(
"\$ ${cart.cartItems[index].price}",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
)),
],
),
),
Positioned(
child: IconButton(
tooltip: "Delete item",
onPressed: () {
cart.remove(cart.cartItems[index]);
print("item deleted from cart");
},
icon: Icon(
Icons.delete,
color: Colors.red,
)),
bottom: 7.5,
right: 7.5,
)
],
));
}),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/LoginScreen.dart
|
import 'package:catalog/Screens/HomePage.dart';
import 'package:catalog/Screens/signup.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:shared_preferences/shared_preferences.dart';
const users = const {
'dribbble@gmail.com': '12345',
'hunter@gmail.com': 'hunter',
};
class LoginScreen extends StatefulWidget {
final pref;
LoginScreen({required this.pref});
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
Duration get loginTime => Duration(milliseconds: 2250);
Future<String?> _authUser(LoginData data) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
print("This is password ${preferences.getString('password')}");
print(data);
print('Name: ${data.name}, Password: ${data.password}');
return Future.delayed(loginTime).then((_) {
if (preferences.getString('email') != data.name) {
return 'User not exists';
}
if (preferences.getString('password') != data.password) {
return 'Password does not match';
}
return null;
});
}
Future<String?> _signUp(LoginData data) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
if (preferences.getString('email') != null) {
return 'Account alredy exists try to login';
}
if (preferences.getString('email') == null) {
preferences.setString('email', '${data.name}');
preferences.setString('password', '${data.password}');
return null;
}
return null;
}
Future<String> _recoverPassword(String name) {
print('Name: $name');
return Future.delayed(loginTime).then((_) {
if (!users.containsKey(name)) {
return 'User not exists';
}
return 'undefined';
});
}
getdata() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var e = preferences.getString('email');
return e;
}
@override
Widget build(BuildContext context) {
return FlutterLogin(
title: 'Apple Store',
theme: LoginTheme(
pageColorLight: Color(0xff00cdac).withOpacity(1),
pageColorDark: Color(0xff02aab0)),
logo: 'asset/images/logo.png',
onLogin: _authUser,
onSignup: _signUp,
onSubmitAnimationCompleted: () async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var email = preferences.getString('email');
var pass = preferences.getString('password');
var name = preferences.getString('name');
if (name == null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (c) =>
Signup(email: email, pass: pass, pref: widget.pref)));
}
if (name != null && email != null) {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (c) => HomePage(pref: widget.pref)));
}
},
onRecoverPassword: _recoverPassword,
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/HomePage.dart
|
import 'package:catalog/Home%20page%20widgets/HomepageWidgets.dart';
import 'package:catalog/Helper/search.dart';
import 'package:catalog/Screens/LoginScreen.dart';
import 'package:catalog/Screens/profile.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class HomePage extends StatefulWidget {
final pref;
const HomePage({Key? key, required this.pref}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late TextEditingController _textEditingController;
bool searchEnabled = false;
int currentIndex = 0;
final controller = PageController();
int currentPage = 0;
@override
void initState() {
if (mounted) {
_textEditingController = TextEditingController();
}
super.initState();
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBody: true,
resizeToAvoidBottomInset: false,
bottomNavigationBar: bottomNavBar(),
drawer: drawer(),
body: PageView(
onPageChanged: (page) {
setState(() {
currentPage = page;
});
},
controller: controller,
children: [
HomePageWidget(pref: widget.pref),
SerachBarPage(),
Profile(pref: widget.pref),
],
),
);
}
void displayPrivacyPolicy() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Privacy Policy"),
content: new Text(
"This is prototype of Apple store made for submission of \"Smartknower Major Project\" by Kartik More."),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Ok"),
onPressed: () {
Navigator.pop(context);
},
),
],
),
);
}
void displayAboutApp() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("About app"),
content: new Text(
"This app performs all the basic functionalities of a E-Commerse app as sign in,sign up,product listing,add to cart and many more.It also manages its state with the help of Provider and makes use of Shared Prefernce as data storage."),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Ok"),
onPressed: () {
Navigator.pop(context);
},
),
],
),
);
}
void displayLogoutDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Alert"),
content: new Text("Are you sure you want to Logout."),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoDialogAction(
isDefaultAction: true,
child: new Text(
"Logout",
style: TextStyle(color: Colors.red),
),
onPressed: () {
print("Account Logged Out");
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (c) => LoginScreen(pref: widget.pref)));
},
)
],
),
);
}
Widget drawer() {
return ClipRRect(
borderRadius: BorderRadius.only(
topRight: Radius.circular(10), bottomRight: Radius.circular(10)),
child: Drawer(
child: SafeArea(
child: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
SizedBox(
height: 45,
child: Image.asset('asset/images/logo.png')),
SizedBox(
height: 10,
),
Text(
"Apple Store",
style: TextStyle(fontSize: 30),
),
SizedBox(
height: 10,
),
Text(
"Prototype of apple store",
style: TextStyle(fontSize: 12),
)
],
),
),
Divider(
thickness: 3,
indent: 20,
endIndent: 20,
),
ListTile(
leading: Icon(Icons.account_box_rounded),
title: Text("Profile"),
onTap: () {
Get.to(() => Profile(pref: widget.pref));
},
),
Divider(
indent: 20,
endIndent: 20,
),
ListTile(
leading: Icon(Icons.privacy_tip_rounded),
title: Text(
'Privacy Policy',
),
onTap: () {
displayPrivacyPolicy();
},
),
Divider(
indent: 20,
endIndent: 20,
),
ListTile(
title: Text("Logout"),
leading: Icon(
Icons.logout_rounded,
color: Colors.black,
),
onTap: () {
displayLogoutDialog();
},
),
Divider(
indent: 20,
endIndent: 20,
),
ListTile(
leading: Icon(Icons.person),
title: Text("About app"),
onTap: () {
displayAboutApp();
},
),
Divider(
indent: 20,
endIndent: 20,
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('Made with'),
Icon(
Icons.favorite,
color: Colors.red,
),
SizedBox(
height: 1,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('by'),
SizedBox(width: 10),
Text(
'KARTIK MORE',
style: TextStyle(
letterSpacing: 2,
fontWeight: FontWeight.bold,
fontSize: 16),
),
],
),
],
)
],
),
),
),
);
}
Container bottomNavBar() {
return Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey.shade300, spreadRadius: 2, blurRadius: 5),
],
),
child: Padding(
padding: const EdgeInsets.only(bottom: 5, left: 8, right: 8),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(30)),
child: BottomNavigationBar(
currentIndex: currentIndex,
showSelectedLabels: false,
showUnselectedLabels: false,
items: [
BottomNavigationBarItem(
label: 'Home',
icon: Icon(
Icons.home_sharp,
color: Colors.black,
),
),
BottomNavigationBarItem(
label: 'Search',
icon: Icon(
Icons.search_rounded,
color: Colors.black,
),
),
BottomNavigationBarItem(
label: 'Profile',
icon: Icon(
Icons.account_circle_rounded,
color: Colors.black,
),
),
],
onTap: (page) {
controller.animateToPage(page,
duration: Duration(milliseconds: 500), curve: Curves.ease);
setState(() {
currentPage = page;
});
},
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/signup.dart
|
import 'package:catalog/Screens/HomePage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:awesome_card/awesome_card.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Signup extends StatefulWidget {
final email;
final pass;
final pref;
const Signup(
{Key? key, required this.email, required this.pass, required this.pref})
: super(key: key);
@override
_SignupState createState() => _SignupState();
}
class _SignupState extends State<Signup> {
int _selectedValue = 0;
late CardType _selectedCardType;
final name = TextEditingController();
final phone = TextEditingController();
final cardholdername = TextEditingController();
final cardno = TextEditingController();
final cardexp = TextEditingController();
final cvv = TextEditingController();
final bankname = TextEditingController();
@override
void initState() {
super.initState();
getDetails();
}
getDetails() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
if (preferences.getString('name') == null) {
displaySignupDialog();
} else {
displaycontinueDialog();
}
}
void displaySignupDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Sign Up"),
content: new Text("Create a new account"),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Ok"),
onPressed: () {
Navigator.pop(context);
},
)
],
),
);
}
void signupErrorDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Alert"),
content: new Text("Fill all the details"),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: new Text("Ok"),
onPressed: () {
Navigator.pop(context);
},
)
],
),
);
}
void displaycontinueDialog() {
showDialog(
context: context,
builder: (BuildContext context) => new CupertinoAlertDialog(
title: new Text("Alert"),
content: new Text("Account alredy exist"),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: CupertinoButton(
child: Text("Continue"),
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (c) => HomePage(pref: widget.pref)));
}))
],
),
);
}
void _showPicker(BuildContext ctx) {
showCupertinoModalPopup(
context: ctx,
builder: (_) => Container(
width: 300,
height: 250,
child: CupertinoPicker(
backgroundColor: Colors.white,
itemExtent: 30,
scrollController: FixedExtentScrollController(initialItem: 1),
children: [
Text('AmericanExpress'),
Text('dinersClub'),
Text('discover'),
Text('elo'),
Text('jcb'),
Text('maestro'),
Text('masterCard'),
Text('rupay'),
Text('visa'),
Text('other'),
],
onSelectedItemChanged: (value) {
setState(() {
_selectedValue = value;
});
print(_selectedValue);
},
),
),
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
Fluttertoast.showToast(
msg: 'Signup first.',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
);
return false;
},
child: Scaffold(
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 20,
left: 20,
child: Text(
"Sign Up",
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
),
Positioned(
top: 60,
left: 20,
child: Text(
"Create your account",
style: TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.fromLTRB(20, 95, 20, 20),
child: ListView(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CupertinoFormSection(
header: Text("Personal Details"),
children: [
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
maxLength: 15,
controller: name,
placeholder: "Enter name",
),
prefix: Text("Name"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: phone,
maxLength: 10,
keyboardType: TextInputType.number,
placeholder: "Enter phone no",
),
prefix: Text("Phone"),
),
],
),
CupertinoFormSection(
header: Text("User"),
children: [
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
maxLength: 15,
placeholder: widget.email,
placeholderStyle:
TextStyle(fontWeight: FontWeight.w400),
),
prefix: Text("Email"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
obscureText: true,
placeholder: widget.pass,
maxLength: 8,
placeholderStyle:
TextStyle(fontWeight: FontWeight.w400),
),
prefix: Text("Password"),
),
],
),
CupertinoFormSection(
header: Text("Card Details"),
children: [
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: bankname,
maxLength: 18,
placeholder: "Enter Bank name",
),
prefix: Text("Bank Name :"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: cardholdername,
maxLength: 18,
placeholder: "Enter card holder name",
),
prefix: Text("Name :"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: cardno,
keyboardType: TextInputType.number,
maxLength: 19,
placeholder: "Enter card no",
),
prefix: Text("Card No :"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: cardexp,
keyboardType: TextInputType.datetime,
maxLength: 5,
placeholder: "expiry date Eg.02/25",
),
prefix: Text("Card Expiry :"),
),
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: cvv,
keyboardType: TextInputType.number,
maxLength: 3,
placeholder: "Enter cvv",
),
prefix: Text("CVV :"),
),
CupertinoButton(
child: Text("Select card type"),
onPressed: () {
_showPicker(context);
if (_selectedValue == 0) {
setState(() {
_selectedCardType = CardType.masterCard;
});
}
if (_selectedValue == 1) {
setState(() {
_selectedCardType = CardType.dinersClub;
});
}
if (_selectedValue == 2) {
setState(() {
_selectedCardType = CardType.discover;
});
}
if (_selectedValue == 3) {
setState(() {
_selectedCardType = CardType.elo;
});
}
if (_selectedValue == 4) {
setState(() {
_selectedCardType = CardType.jcb;
});
}
if (_selectedValue == 5) {
setState(() {
_selectedCardType = CardType.maestro;
});
}
if (_selectedValue == 6) {
setState(() {
_selectedCardType =
CardType.americanExpress;
});
}
if (_selectedValue == 7) {
setState(() {
_selectedCardType = CardType.rupay;
});
}
if (_selectedValue == 8) {
setState(() {
_selectedCardType = CardType.visa;
});
}
if (_selectedValue == 9) {
setState(() {
_selectedCardType = CardType.other;
});
}
print("${_selectedCardType.toString()}");
}),
],
),
SizedBox(height: 22),
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
elevation: 5,
child: CupertinoButton.filled(
child: Text("Sign Up"),
onPressed: () async {
SharedPreferences preferences =
await SharedPreferences.getInstance();
preferences.setString('name', name.text);
preferences.setString('phone', phone.text);
preferences.setString(
'cardholdername', cardholdername.text);
preferences.setString('cardno', cardno.text);
preferences.setString('cardexp', cardexp.text);
preferences.setString('cvv', cvv.text);
preferences.setString(
'cardtype', _selectedCardType.toString());
preferences.setString(
'bankname', bankname.text);
// displayDialog();
// preferences.remove('name');
// print("${preferences.getString('name')}");
print(name.text);
print(bankname.text);
print(phone.text);
print(cardholdername.text);
print(cardno.text);
print(cardexp.text);
print(cvv.text);
print(_selectedCardType.toString());
if (name.text.isNotEmpty &&
bankname.text.isNotEmpty &&
phone.text.isNotEmpty &&
cardholdername.text.isNotEmpty &&
cardno.text.isNotEmpty &&
cardexp.text.isNotEmpty &&
cvv.text.isNotEmpty) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (c) =>
HomePage(pref: widget.pref)));
} else {
signupErrorDialog();
}
},
borderRadius:
const BorderRadius.all(Radius.circular(20.0)),
),
),
),
),
],
),
],
),
),
],
)),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Screens/SplashScreen.dart
|
import 'dart:async';
import 'package:catalog/Screens/HomePage.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'LoginScreen.dart';
// import 'dashboard_screen.dart';
// import 'package:permission_handler/permission_handler.dart';
class SplashScreen extends StatefulWidget {
final pref;
SplashScreen({required this.pref});
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
getName() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var name = preferences.getString('name');
var email = preferences.getString('email');
if (name == null && email == null) {
Timer(
Duration(seconds: 2),
() => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(pref: widget.pref))));
}
if (name != null && email != null) {
Timer(
Duration(seconds: 2),
() => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (c) => HomePage(pref: widget.pref))));
// MaterialPageRoute(
// builder: (context) => DashboardScreen(
// name: email,
// ))));
}
//logout condition
if (name != null && email == null) {
Timer(
Duration(seconds: 2),
() => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(pref: widget.pref))));
}
if (name == null && email != null) {
Timer(
Duration(seconds: 2),
() => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => LoginScreen(pref: widget.pref))));
}
}
@override
void initState() {
//go to home screen
getName();
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'asset/images/logo.png',
height: 135,
),
SizedBox(
height: 15,
),
Text(
"Apple Store",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
SizedBox(
height: 5,
),
Text(
"Prototype of Apple store ",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Made with "),
Icon(
Icons.favorite,
color: Colors.red,
),
Text(" by KARTIK MORE.")
],
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/model/providerModel.dart
|
import 'package:flutter/material.dart';
// class SearchBar extends ChangeNotifier {
// bool serachbarEnabled = false;
// void activateSerachbar() {
// print("$serachbarEnabled");
// serachbarEnabled = true;
// notifyListeners();
// print("in to the provider and $serachbarEnabled");
// }
// }
class Items {
final name;
final price;
final imagename;
Items({required this.name, required this.price, required this.imagename});
}
class CartModel extends ChangeNotifier {
final List<Items> _items = [];
// int get totalPrice => FlutterCart().getTotalAmount();
List<Items> get cartItems => _items; //get items from the cart
int get listlength => _items.length; //get the length of list for builder
// int get totalPrice => _items.fold(0,total,_items[index].price) => total + _items[index].price);
double get totalPrice =>
cartItems.fold(0, (total, current) => total + current.price);
void add(Items item) {
_items.add(item);
notifyListeners();
}
void remove(Items item) {
_items.remove(item);
notifyListeners();
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/model/model.dart
|
class Item {
String description, name;
Item({required this.name, required this.description});
}
List<Item> iphones = [
Item(name: "iphoneX", description: '''• 256 GB ROM
• 14.73 cm (5.8 inch) Super Retina HD Display
• 12MP + 12MP | 7MP Front Camera
• A11 Bionic Chip with 64-bit Architecture, Neural Engine, Embedded M11 Motion Coprocessor Processor'''),
Item(name: "iphone12", description: '''• 64 GB ROM
• 15.49 cm (6.1 inch) Super Retina XDR Display
• 12MP + 12MP | 12MP Front Camera
• A14 Bionic Chip with Next Generation Neural Engine Processor
• Ceramic Shield
• IP68 Water Resistance
• All Screen OLED Display'''),
Item(name: "iphoneXmax", description: '''• 64 GB ROM
• 16.51 cm (6.5 inch) Super Retina HD Display
• 12MP + 12MP | 7MP Front Camera
• A12 Bionic Chip Processor
• iOS 13 Compatible'''),
Item(name: 'iphone11', description: '''• 128 GB ROM
• 15.49 cm (6.1 inch) Liquid Retina HD Display
• 12MP + 12MP | 12MP Front Camera
• A13 Bionic Chip Processor'''),
Item(name: 'iphone1164', description: '''• 64 GB ROM
• 15.49 cm (6.1 inch) Liquid Retina HD Display
• 12MP + 12MP | 12MP Front Camera
• A13 Bionic Chip Processor'''),
Item(name: 'iphone7', description: '''• 128 GB ROM
• 11.94 cm (4.7 inch) Retina HD Display
• 12MP Rear Camera | 7MP Front Camera
• Apple A10 Fusion 64-bit processor and Embedded M10 Motion Co-processor'''),
];
List<Item> macbook = [
Item(
name: "macair",
description:
'''• Apple-designed M1 chip for a giant leap in CPU, GPU, and machine learning performance
• Go longer than ever with up to 18 hours of battery life
• 8-core CPU delivers up to 3.5x faster performance to tackle projects faster than ever
• Up to eight GPU cores with up to 5x faster graphics for graphics-intensive apps and games
• 16-core Neural Engine for advanced machine learning
• 8GB of unified memory so everything you do is fast and fluid
• Superfast SSD storage launches apps and opens files in an instant
• Fanless design for silent operation
• 13.3-inch Retina display with P3 wide color for vibrant images and incredible detail
• FaceTime HD camera with advanced image signal processor for clearer, sharper video calls'''),
Item(name: "macpro13", description: '''
Operating System Mac OS
Graphics Coprocessor Intel Iris Plus
Hardware Interface USB 3.1 Type C, Thunderbolt, Headphone, Bluetooth 5
Screen Size 13.3 Inches
Brand Apple
About this item
• Tenth-generation quad-core Intel Core i5 processor
• Brilliant Retina display with True Tone technology
• Backlit Magic Keyboard
• Touch Bar and Touch ID
• Intel Iris Plus Graphics
'''),
Item(name: "macpro16", description: '''Hardware Interface USB Type C
Screen Size 16 Inches
Brand Apple
Graphics Processor Manufacturer AMD
CPU Manufacturer Intel
About this item
• 16" MacBook Pro with Touch Bar - 96W USB-C Power Adapter - USB-C Charge Cable (2m) - Apple 1 Year Limited Warranty
• Stunning 16" Retina display with True Tone technology
• Touch Bar and Touch ID
• Ultrafast SSD
• Six-speaker system with force-cancelling woofers'''),
Item(name: "macpro m1", description: '''Operating System Mac OS
Hardware Interface Thunderbolt, Bluetooth 5, USB 3.2 Gen 2
Screen Size 13.3 Inches
Brand Apple
Graphics Processor Manufacturer Apple
About this item
• Apple-designed M1 chip for a giant leap in CPU, GPU, and machine learning performance
• Get more done with up to 20 hours of battery life, the longest ever in a Mac
• 8-core CPU delivers up to 2.8x faster performance to fly through workflows quicker than ever
• 8-core GPU with up to 5x faster graphics for graphics-intensive apps and games
• 16-core Neural Engine for advanced machine learning'''),
Item(name: "imac", description: '''
Operating System Mac OS
Brand Apple
Color Pink
CPU Model Unknown
Hard Disk Description PCIe-based SSD
Hardware Interface USB Type C, Ethernet, Thunderbolt 4
About this item
• Immersive 24-inch 4.5K Retina display with P3 wide color gamut and 500 nits of brightness
• Apple M1 chip delivers powerful performance with 8-core CPU and 7-core GPU
• Strikingly thin 11.5 mm design in vibrant colors
• 1080p FaceTime HD camera with M1 ISP for amazing video quality
• Studio-quality three-mic array for crystal clear calls and voice recordings
• Six-speaker sound system for a remarkably robust and high-quality audio experience
• Up to 256GB of ultrafast SSD storage
• Two Thunderbolt / USB 4 ports and up to two USB 3 ports
• Ultrafast Wi-Fi 6 and Bluetooth 5.0 wireless
• Color-matched Magic Mouse with Magic Keyboard or Magic Keyboard with Touch ID'''),
Item(name: "imac", description: '''
Operating System Mac OS
Brand Apple
Color Orange
CPU Model Unknown
Hard Disk Description PCIe-based SSD
Hardware Interface USB Type C, Ethernet, Thunderbolt 4
About this item
• Immersive 27-inch 4.5K Retina display with P3 wide color gamut and 500 nits of brightness
• Apple M1 chip delivers powerful performance with 8-core CPU and 7-core GPU
• Strikingly thin 11.5 mm design in vibrant colors
• 1080p FaceTime HD camera with M1 ISP for amazing video quality
• Studio-quality three-mic array for crystal clear calls and voice recordings
• Six-speaker sound system for a remarkably robust and high-quality audio experience
• Up to 256GB of ultrafast SSD storage
• Two Thunderbolt / USB 4 ports and up to two USB 3 ports
• Ultrafast Wi-Fi 6 and Bluetooth 5.0 wireless
• Color-matched Magic Mouse with Magic Keyboard or Magic Keyboard with Touch ID'''),
];
List<Item> ipad = [
Item(name: 'ipadpro 12', description: '''
Brand Apple
Operating System IPadOS
Wireless Communication Technology Bluetooth, Wi-Fi, NFC
Hardware Interface Thunderbolt
Screen Size 12.9 Inches
About this item
• Apple M1 chip for next-level performance
• Brilliant 12.9-inch Liquid Retina XDR display with ProMotion, True Tone, and P3 wide color
• TrueDepth camera system featuring Ultra Wide camera with Center Stage
• 12MP Wide camera, 10MP Ultra Wide camera, and LiDAR Scanner for immersive AR
• Stay connected with ultrafast Wi-Fi
• Go further with all-day battery life
• Thunderbolt port for connecting to fast external storage, displays, and docks
• Face ID for secure authentication and Apple Pay
• Four speaker audio and five studio-quality microphones
• Support for Apple Pencil (2nd generation), Magic Keyboard, and Smart Keyboard Folio'''),
Item(name: '', description: '''Brand Apple
Operating System IPadOS
Wireless Communication Technology Bluetooth, Wi-Fi
Hardware Interface USB Type C, Bluetooth 5
Screen Size 10.9 Inches
About this item
• Stunning 10.9-inch Liquid Retina display with True Tone and P3 wide color
• A14 Bionic chip with Neural Engine
• Touch ID for secure authentication and Apple Pay
• 12MP back camera, 7MP FaceTime HD front camera
• Available in Silver, Space Gray, Rose Gold, Green, and Sky Blue
• Wide stereo audio
• Wi-Fi 6 (802.11ax)
• Up to 10 hours of battery life
• USB-C connector for charging and accessories
• Support for Magic Keyboard, Smart Keyboard Folio, and Apple Pencil (2nd generation)'''),
Item(name: 'ipadpro 11', description: '''
Brand Apple
Operating System IPadOS
Wireless Communication Technology Bluetooth, Wi-Fi, NFC
Hardware Interface Thunderbolt
Screen Size 11 Inches
About this item
• Apple M1 chip for next-level performance
• Stunning 11-inch Liquid Retina display with ProMotion, True Tone, and P3 wide color
• TrueDepth camera system featuring Ultra Wide front camera with Center Stage
• 12MP Wide camera, 10MP Ultra Wide camera, and LiDAR Scanner for immersive AR
• Stay connected with ultrafast Wi-Fi
• Go further with all-day battery life
• Thunderbolt port for connecting to fast external storage, displays, and docks
• Face ID for secure authentication and Apple Pay
• Four speaker audio and five studio-quality microphones
• Support for Apple Pencil (2nd generation), Magic Keyboard, and Smart Keyboard Folio'''),
Item(name: 'ipad 10', description: '''
Brand Apple
Operating System IPadOS
Wireless Communication Technology Bluetooth, Wi-Fi
Hardware Interface Lightning, Bluetooth 4.0, 3.5mm Audio
Graphics Coprocessor A12
About this item
• Gorgeous 10.2-inch Retina display
• A12 Bionic chip with Neural Engine
• Support for Apple Pencil (1st generation) and Smart Keyboard
• 8MP back camera, 1.2MP FaceTime HD front camera
• Stereo speakers'''),
Item(name: 'ipad 7', description: '''Brand Apple
Operating System IPadOS
Wireless Communication Technology Bluetooth, Wi-Fi
Hardware Interface Lightning, 3.5mm Audio, Bluetooth 5, 802.11 ac/b/g/n
Graphics Coprocessor A12
About this item
• 7.9-inch Retina Display with True Tone and wide Color
• A12 Bionic chip
• Touch ID fingerprint sensor
• 8MP back camera, 7MP FaceTime HD front camera
• Stereo speakers''')
];
List<Item> watches = [
Item(name: 'watchs6+', description: '''
Supported Application Fitness Tracker, Sleep Monitor, Voice Assistant, Elevation Tracker, Heart Rate Monitor
Brand Apple
Wireless Communication Standard Bluetooth, 5 GHz Radio Frequency, 802.11a/b/g/n, 2.4 GHz Radio Frequency
Color Aluminum Case with PRODUCT(RED) - Sport Band
Connectivity Technology Cellular, Wi-Fi, NFC, GPS
Operating System WatchOS
Band Color Red
Human Interface Input Touchscreen, Dial, Microphone
Screen Size 40 Millimeters
Water Resistance Level Water Resistant'''),
Item(name: 'watchs6', description: '''
Supported Application Fitness Tracker, Sleep Monitor, Voice Assistant, Elevation Tracker, Heart Rate Monitor
Brand Apple
Wireless Communication Standard 5 GHz Radio Frequency, Bluetooth, 802.11a/b/g/n, 2.4 GHz Radio Frequency
Color Space Gray Aluminum Case with Black Sport Band
Connectivity Technology Bluetooth, Wi-Fi, NFC, GPS
Operating System WatchOS
Band Color Black
Human Interface Input Touchscreen, Dial
Screen Size 40 Millimeters
Water Resistance Level Water Resistant'''),
Item(name: 'watchse+', description: '''
Supported Application Fitness Tracker, Sleep Monitor, Voice Assistant, Elevation Tracker, Heart Rate Monitor
Brand Apple
Wireless Communication Standard Bluetooth, 802.11a/b/g/n, 2.4 GHz Radio Frequency
Color Space Gray Aluminum Case with Pink Sport Band
Connectivity Technology Cellular, Bluetooth, Wi-Fi, NFC, GPS
Operating System WatchOS
Band Color Pink
Human Interface Input Touchscreen, Dial
Screen Size 40 Millimeters
Water Resistance Level Water Resistant'''),
Item(name: 'watchse', description: '''
Supported Application Fitness Tracker, Voice Assistant, Elevation Tracker, GPS, Heart Rate Monitor
Brand Apple
Wireless Communication Standard Bluetooth, 802.11a/b/g/n, 2.4 GHz Radio Frequency
Color Silver Aluminum Case with Deep Navy Sport Loop
Connectivity Technology Cellular, Bluetooth, Wi-Fi, NFC, GPS
Operating System WatchOS
Band Color Deep Navy
Human Interface Input Touchscreen, Dial, Microphone
Screen Size 40 Millimeters
Water Resistance Level Water Resistant'''),
Item(name: 'watchs5', description: '''
Supported Application GPS
Brand Apple
Color Silver Aluminum with White Sport Band
Connectivity Technology GPS
Operating System WatchOS
Case Material Aluminum
GPS True
Battery Cell Composition Lithium Ion'''),
Item(
name: 'watch3',
description:
'''Supported Application Fitness Tracker, Sleep Monitor, GPS, Pedometer, Heart Rate Monitor
Brand Apple
Wireless Communication Standard Bluetooth, 802.11a/b/g/n
Color Space Gray Aluminum with Gold Sport Band
Connectivity Technology Bluetooth, Wi-Fi, GPS
Operating System WatchOS
Band Color Black
Compatible Devices IPhone 5s or later
Human Interface Input Touchscreen, Dial
Screen Size 38 Millimeters'''),
];
List<Item> airpods = [
Item(name: 'airpodsmax', description: '''Brand Apple
Color Space Gray
Connectivity Technology NFC, Bluetooth, Transparancy, Audio Sharing, Wireless
Model Name AirPods Max
Form Factor Over Ear
About this item
Apple-designed dynamic driver provides high-fidelity audio
Active Noise Cancellation blocks outside noise, so you can immerse yourself in music
Transparency mode for hearing and interacting with the world around you
Spatial audio with dynamic head tracking provides theater-like sound that surrounds you
Computational audio combines custom acoustic design with the Apple H1 chip and software for breakthrough listening experiences
Designed with a knit-mesh canopy and memory foam ear cushions for an exceptional fit
Magical experience with effortless setup, on-head detection, and seamless switching between devices'''),
Item(name: 'airpodspro', description: '''Brand Apple
Color White
Connectivity Technology Wireless
Model Name Apple AirPods Pro
Form Factor In Ear
About this item
Active noise cancellation for immersive sound
Transparency mode for hearing and connecting with the world around you
Three sizes of soft, tapered silicone tips for a customizable fit
Sweat and water resistant
Adaptive EQ automatically tunes music to the shape of your ear
Easy setup for all your Apple devices
Quick access to Siri by saying “Hey Siri”
The Wireless Charging Case delivers more than 24 hours of battery life'''),
Item(name: 'airpodsWC', description: '''Brand Apple
Color White
Connectivity Technology Bluetooth, NFC
Model Name Apple AirPods with Wireless Charging Case
Form Factor In Ear
About this item
Universal fit that’s comfortable all day
Automatically on, automatically connected
Easy setup for all your Apple devices
Quick access to Siri by saying “Hey Siri”
Seamless switching between devices'''),
Item(name: 'airpods', description: '''Brand Apple
Color White
Connectivity Technology Wireless
Model Name Apple AirPods with Wired Charging Case
Form Factor In Ear
About this item
Automatically on, automatically connected
Easy setup for all your Apple devices
Quick access to Siri by saying “Hey Siri”
Double-tap to play or skip forward
New Apple H1 headphone chip delivers faster wireless connection to your devices'''),
];
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/ProductView/airpodsview.dart
|
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/model.dart';
class ProductViewForAirPods extends StatefulWidget {
final imageName;
final productName;
final int price;
final String tag;
const ProductViewForAirPods({
Key? key,
required this.imageName,
required this.tag,
required this.productName,
required this.price,
}) : super(key: key);
@override
_ProductViewForAirPodsState createState() => _ProductViewForAirPodsState();
}
class _ProductViewForAirPodsState extends State<ProductViewForAirPods> {
String id = "0";
@override
void initState() {
print("${int.parse(widget.tag)}");
setState(() {
id = widget.tag;
});
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.read<CartModel>();
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, Colors.lightGreenAccent])),
child: Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Positioned(
top: 17,
left: 60,
child: Container(
child: Hero(
tag: '${widget.tag}',
child: Align(
alignment: Alignment.topCenter,
child: Image.asset(
'asset/images/${widget.imageName}.png',
height: 280,
width: 250,
),
)),
),
),
Positioned(
top: 270,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 25,
color: Colors.grey.shade800,
),
]),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
top: 12,
left: 27,
child: Text(
"${widget.productName}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 40,
left: 27,
child: Text(
"Highlights",
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
)),
Positioned(
top: 72,
left: 20,
child: Container(
height: 170,
width: 300,
child: ListView(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
children: [
Text(
"${airpods[int.parse(id) - 1].description}",
style: TextStyle(fontSize: 15.8),
),
],
),
)),
Positioned(
top: 250,
left: 30,
child: Text(
"\$ ${widget.price}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 240,
right: 30,
child: MaterialButton(
height: 40,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.black,
onPressed: () {
cart.add(Items(
imagename: widget.imageName,
name: widget.productName,
price: widget.price));
print("added to cart");
Fluttertoast.showToast(
msg: "${widget.productName} added to cart.",
gravity: ToastGravity.BOTTOM);
},
child: Text(
"Add to cart",
style: TextStyle(
fontSize: 20, color: Colors.white),
))),
],
),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/ProductView/ipadview.dart
|
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/model.dart';
class ProductViewForiPad extends StatefulWidget {
final imageName;
final productName;
final int price;
final String tag;
const ProductViewForiPad({
Key? key,
required this.imageName,
required this.tag,
required this.productName,
required this.price,
}) : super(key: key);
@override
_ProductViewForiPadState createState() => _ProductViewForiPadState();
}
class _ProductViewForiPadState extends State<ProductViewForiPad> {
String id = "0";
@override
void initState() {
print("${int.parse(widget.tag)}");
setState(() {
id = widget.tag;
});
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.read<CartModel>();
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, Colors.pinkAccent])),
child: Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Positioned(
top: 17,
left: 60,
child: Container(
child: Hero(
tag: '${widget.tag}',
child: Align(
alignment: Alignment.topCenter,
child: Image.asset(
'asset/images/${widget.imageName}.png',
height: 280,
width: 250,
),
)),
),
),
Positioned(
top: 300,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 25,
color: Colors.grey.shade800,
),
]),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
top: 12,
left: 27,
child: Text(
"${widget.productName}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 37,
left: 27,
child: Text(
"Highlights",
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
)),
Positioned(
top: 65,
left: 20,
child: Container(
height: 145,
width: 300,
child: ListView(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
children: [
Text(
"${ipad[int.parse(id) - 1].description}",
style: TextStyle(fontSize: 15.8),
),
],
),
)),
Positioned(
top: 220,
left: 30,
child: Text(
"\$ ${widget.price}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 212,
right: 30,
child: MaterialButton(
height: 40,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.black,
onPressed: () {
cart.add(Items(
imagename: widget.imageName,
name: widget.productName,
price: widget.price));
print("added to cart");
Fluttertoast.showToast(
msg: "${widget.productName} added to cart.",
gravity: ToastGravity.BOTTOM);
},
child: Text(
"Add to cart",
style: TextStyle(
fontSize: 20, color: Colors.white),
))),
],
),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/ProductView/macview.dart
|
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/model.dart';
class ProductViewForMac extends StatefulWidget {
final imageName;
final productName;
final int price;
final String tag;
const ProductViewForMac(
{Key? key,
required this.imageName,
required this.tag,
required this.productName,
required this.price})
: super(key: key);
@override
_ProductViewForMacState createState() => _ProductViewForMacState();
}
class _ProductViewForMacState extends State<ProductViewForMac> {
String id = "0";
@override
void initState() {
setState(() {
id = widget.tag;
});
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.read<CartModel>();
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, Colors.blue])),
child: Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Container(
child: Hero(
tag: '${widget.tag}',
child: Align(
alignment: Alignment.topCenter,
child: Image.asset(
'asset/images/${widget.imageName}.png',
height: 300,
width: 250,
),
)),
),
Positioned(
top: 250,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 25,
color: Colors.grey.shade800,
),
]),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
top: 12,
left: 27,
child: Text(
"${widget.productName}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 37,
left: 27,
child: Text(
"Highlights",
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
)),
Positioned(
top: 65,
left: 20,
child: Container(
height: 170,
width: 300,
child: ListView(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
children: [
Text(
"${macbook[int.parse(id) - 1].description}",
style: TextStyle(fontSize: 15.8),
),
],
),
)),
Positioned(
top: 260,
left: 30,
child: Text(
"\$ ${widget.price}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 250,
right: 30,
child: MaterialButton(
height: 40,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.black,
onPressed: () {
cart.add(Items(
imagename: widget.imageName,
name: widget.productName,
price: widget.price));
Fluttertoast.showToast(
msg: "${widget.productName} added to cart.",
gravity: ToastGravity.BOTTOM);
print("added to cart");
},
child: Text(
"Add to cart",
style: TextStyle(
fontSize: 20, color: Colors.white),
))),
],
),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/ProductView/watchview.dart
|
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/model.dart';
class ProductViewForWatch extends StatefulWidget {
final imageName;
final productName;
final int price;
final String tag;
const ProductViewForWatch({
Key? key,
required this.imageName,
required this.tag,
required this.productName,
required this.price,
}) : super(key: key);
@override
_ProductViewForWatchState createState() => _ProductViewForWatchState();
}
class _ProductViewForWatchState extends State<ProductViewForWatch> {
String id = "0";
@override
void initState() {
print("${int.parse(widget.tag)}");
setState(() {
id = widget.tag;
});
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.read<CartModel>();
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, Colors.orange.shade700])),
child: Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Positioned(
top: 17,
left: 60,
child: Container(
child: Hero(
tag: '${widget.tag}',
child: Align(
alignment: Alignment.topCenter,
child: Image.asset(
'asset/images/${widget.imageName}.png',
height: 280,
width: 250,
),
)),
),
),
Positioned(
top: 290,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 25,
color: Colors.grey.shade800,
),
]),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
top: 12,
left: 27,
child: Text(
"${widget.productName}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 40,
left: 27,
child: Text(
"Highlights",
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
)),
Positioned(
top: 72,
left: 20,
child: Container(
height: 150,
width: 300,
child: ListView(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
children: [
Text(
"${watches[int.parse(id) - 1].description}",
style: TextStyle(fontSize: 15.8),
),
],
),
)),
Positioned(
top: 235,
left: 30,
child: Text(
"\$ ${widget.price}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 225,
right: 30,
child: MaterialButton(
height: 40,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.black,
onPressed: () {
cart.add(Items(
imagename: widget.imageName,
name: widget.productName,
price: widget.price));
print("added to cart");
Fluttertoast.showToast(
msg: "${widget.productName} added to cart.",
gravity: ToastGravity.BOTTOM);
},
child: Text(
"Add to cart",
style: TextStyle(
fontSize: 20, color: Colors.white),
))),
],
),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/ProductView/iphoneview.dart
|
import 'package:catalog/model/providerModel.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../model/model.dart';
class ProductViewForIphone extends StatefulWidget {
final imageName;
final productName;
final int price;
final String tag;
const ProductViewForIphone({
Key? key,
required this.imageName,
required this.tag,
required this.productName,
required this.price,
}) : super(key: key);
@override
_ProductViewForIphoneState createState() => _ProductViewForIphoneState();
}
class _ProductViewForIphoneState extends State<ProductViewForIphone> {
String id = "0";
@override
void initState() {
print("${int.parse(widget.tag)}");
setState(() {
id = widget.tag;
});
super.initState();
}
@override
Widget build(BuildContext context) {
var cart = context.read<CartModel>();
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.white, Colors.amber.shade600])),
child: Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Stack(
children: [
Positioned(
top: 10,
left: 10,
child: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios_new_rounded))),
Container(
child: Hero(
tag: '${widget.tag}',
child: Align(
alignment: Alignment.topCenter,
child: Image.asset(
'asset/images/${widget.imageName}.png',
height: 300,
width: 250,
),
)),
),
Positioned(
top: 300,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
spreadRadius: 5,
offset: Offset(15.0, 15.0),
blurRadius: 25,
color: Colors.grey.shade800,
),
]),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
top: 12,
left: 27,
child: Text(
"${widget.productName}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 37,
left: 27,
child: Text(
"Highlights",
style: TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
)),
Positioned(
top: 65,
left: 20,
child: Container(
height: 145,
width: 300,
child: ListView(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
children: [
Text(
"${iphones[int.parse(id) - 1].description}",
style: TextStyle(fontSize: 15.8),
),
],
),
)),
Positioned(
top: 220,
left: 30,
child: Text(
"\$ ${widget.price}",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 22),
)),
Positioned(
top: 212,
right: 30,
child: MaterialButton(
height: 40,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.black,
onPressed: () {
print("${cart.cartItems.toString()}");
cart.add(Items(
imagename: widget.imageName,
name: widget.productName,
price: widget.price));
Fluttertoast.showToast(
msg: "${widget.productName} added to cart.",
gravity: ToastGravity.BOTTOM);
print("added to cart");
},
child: Text(
"Add to cart",
style: TextStyle(
fontSize: 20, color: Colors.white),
))),
],
),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Apple-Store/lib
|
mirrored_repositories/Flutter-Apple-Store/lib/Helper/ItemContainer.dart
|
import 'package:catalog/ProductView/airpodsview.dart';
import 'package:catalog/ProductView/ipadview.dart';
import 'package:catalog/ProductView/iphoneview.dart';
import 'package:catalog/ProductView/macview.dart';
import 'package:catalog/ProductView/watchview.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class ItemContainer extends StatelessWidget {
final String name;
final imagename;
final String tag;
final double height;
final int itemId, price;
const ItemContainer({
Key? key,
required this.name,
required this.price,
required this.imagename,
required this.tag,
required this.height,
required this.itemId,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
if (itemId == 1) {
Get.to(() => ProductViewForIphone(
imageName: '$imagename',
tag: '$tag',
price: price,
productName: '$name',
));
}
if (itemId == 2) {
Get.to(() => ProductViewForMac(
imageName: '$imagename',
tag: '$tag',
price: price,
productName: '$name',
));
}
if (itemId == 3) {
Get.to(() => ProductViewForiPad(
imageName: '$imagename',
tag: '$tag',
price: price,
productName: '$name',
));
}
if (itemId == 4) {
Get.to(() => ProductViewForWatch(
imageName: '$imagename',
tag: '$tag',
price: price,
productName: '$name',
));
}
if (itemId == 5) {
Get.to(() => ProductViewForAirPods(
imageName: '$imagename',
tag: '$tag',
price: price,
productName: '$name',
));
}
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
spreadRadius: 2.2,
offset: Offset(10.0, 10.0),
blurRadius: 8.0,
color: Colors.black87.withOpacity(0.05),
),
]),
height: 10,
width: 9,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Hero(
tag: '$tag',
child: Image.asset(
'asset/images/$imagename.png',
height: height,
),
),
SizedBox(height: 5),
Text(
"$name",
style: TextStyle(fontWeight: FontWeight.w500),
),
SizedBox(height: 2),
Text(
"\$ $price",
style: TextStyle(fontWeight: FontWeight.w600),
),
],
),
),
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.