repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/widgets/emoji_widget.dart | import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
class EmojiWidget extends StatelessWidget {
final Function onEmojiSelected;
final Function onBackspacePressed;
const EmojiWidget(
{Key key,
@required this.onEmojiSelected,
@required this.onBackspacePressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return EmojiPicker(
onEmojiSelected: onEmojiSelected,
onBackspacePressed: onBackspacePressed,
config: const Config(
columns: 7,
emojiSizeMax: 32.0,
verticalSpacing: 0,
horizontalSpacing: 0,
initCategory: Category.RECENT,
bgColor: ThemeConfig.emojiWidgetBackgroundColor,
indicatorColor: ThemeConfig.emojiWidgetPrimaryColor,
iconColor: ThemeConfig.emojiWidgetIconColor,
iconColorSelected: ThemeConfig.emojiWidgetPrimaryColor,
progressIndicatorColor: ThemeConfig.emojiWidgetPrimaryColor,
backspaceColor: ThemeConfig.emojiWidgetPrimaryColor,
showRecentsTab: true,
recentsLimit: 28,
noRecentsText: 'No Recents',
categoryIcons: CategoryIcons(),
// buttonMode: ButtonMode.MATERIAL,
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/widgets/widgets.dart | export 'chatting_app_bar.dart';
export 'message_widget.dart';
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/widgets/message_text_field.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
class MessageTextField extends StatelessWidget {
final FocusNode focusNode;
final TextEditingController textEditingController;
const MessageTextField({
Key key,
@required this.focusNode,
@required this.textEditingController,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
child: TextField(
focusNode: focusNode,
controller: textEditingController,
style: Theme.of(context).textTheme.bodyText1,
decoration: InputDecoration(
fillColor: Colors.grey[200],
filled: true,
hintText: 'Message...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(ThemeConfig.borderRadius),
borderSide: BorderSide.none,
),
contentPadding: EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 4.0,
),
),
minLines: 1,
maxLines: 3,
keyboardType: TextInputType.multiline,
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/bloc/chatting_event.dart | part of 'chatting_bloc.dart';
abstract class ChattingEvent extends Equatable {
const ChattingEvent();
@override
List<Object> get props => [];
}
class ChattingCheckHasMessagedBefore extends ChattingEvent {}
class ChattingSendMessage extends ChattingEvent {
final String message;
final File image;
ChattingSendMessage({
@required this.message,
this.image,
});
@override
List<Object> get props => [message, image];
}
class ChattingFetchMessages extends ChattingEvent {}
class ChattingUpdateMessages extends ChattingEvent {
final List<Message> messagesList;
ChattingUpdateMessages({
@required this.messagesList,
});
@override
List<Object> get props => [messagesList];
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/bloc/chatting_bloc.dart | import 'dart:async';
import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
part 'chatting_event.dart';
part 'chatting_state.dart';
class ChattingBloc extends Bloc<ChattingEvent, ChattingState> {
final MessagesRepository _messagesRepository;
StreamSubscription<List<Message>> _messagesSubscription;
StreamSubscription<bool> _messageDbExists;
ChattingBloc({
@required MessagesRepository messagesRepository,
@required String userId,
DocumentReference messagesRef,
}) : _messagesRepository = messagesRepository,
super(
ChattingState.initial(userId: userId, messagesDbRef: messagesRef)) {
add(ChattingCheckHasMessagedBefore());
}
@override
Future<void> close() async {
_messagesSubscription?.cancel();
_messageDbExists?.cancel();
super.close();
}
@override
Stream<ChattingState> mapEventToState(
ChattingEvent event,
) async* {
if (event is ChattingCheckHasMessagedBefore) {
yield* _mapCheckHasMessagedBeforeToState();
}
if (event is ChattingSendMessage) {
yield* _mapSendMessageToState(event);
}
if (event is ChattingFetchMessages) {
yield* _mapFetchMessagesToState();
}
if (event is ChattingUpdateMessages) {
yield* _mapUpdateMessagesToState(event);
}
}
// Check if user has messaged this person before
Stream<ChattingState> _mapCheckHasMessagedBeforeToState() async* {
try {
if (state.messagesDbRef != null) {
// Navigated from chatScreen
// Therefore user must have messaged this person before
// And messagesDbRef is present so we can fetch all the messages
yield (state.copyWith(hasMessagedBefore: true));
add(ChattingFetchMessages());
} else {
// Navigated from usersScreen
// Therefore we have to check to see if user has messaged this person before
final check =
await _messagesRepository.checkMessagesExists(userId: state.userId);
if (check == true) {
// User has messaged this person before
final messagesDb = await _messagesRepository
.getAlreadyPresentMessagesDb(userId: state.userId);
yield (state.copyWith(
messagesDbRef: messagesDb, hasMessagedBefore: true));
add(ChattingFetchMessages());
} else {
// User has no messages with this person
_messageDbExists?.cancel();
_messageDbExists = _messagesRepository
.messageExistsStream(userId: state.userId)
.listen((exists) {
if (exists) {
// The user has send a message while
// this user is in chatting screen
add(ChattingCheckHasMessagedBefore());
_messageDbExists.cancel();
}
});
yield (state.copyWith(hasMessagedBefore: false));
}
}
} catch (e) {
yield (state.copyWith(status: ChattingStatus.error, error: e.message));
}
}
// Sending a new message
Stream<ChattingState> _mapSendMessageToState(
ChattingSendMessage event) async* {
yield (state.copyWith(
isSending: true)); // To show the LinearProgressIndicator
try {
if (state.hasMessagedBefore) {
// User already has a messageDb with this person therefore we just add the message to it
await _messagesRepository.sendMessage(
recipientId: state.userId,
documentReference: state.messagesDbRef,
message: event.message,
image: event.image,
);
} else {
// User has no messageDb with this person
// We create the db and send the first message
final messagesDbRef = await _messagesRepository.sendFirstMessage(
userId: state.userId,
message: event.message,
image: event.image,
);
// We add the messagesDb to state
yield state.copyWith(messagesDbRef: messagesDbRef);
// Now checking for has messaged before will be true and it will load the messages
add(ChattingCheckHasMessagedBefore());
}
yield (state.copyWith(
isSending: false)); // To hide the LinearProgressIndicator
} catch (e) {
yield (state.copyWith(
status: ChattingStatus.error, error: e.message, isSending: false));
}
}
// Getting the stream of messages
Stream<ChattingState> _mapFetchMessagesToState() async* {
try {
yield (state.copyWith(status: ChattingStatus.loading));
if (state.hasMessagedBefore == false) {
// Double check to ensure user has messaged this person before and messageDb exists
yield (state.copyWith(status: ChattingStatus.loaded));
} else {
// Creating a new messagesSubscription and canceling any old one present
_messagesSubscription?.cancel();
_messagesSubscription = _messagesRepository
.getMessagesList(messagesDbRef: state.messagesDbRef)
.listen((messages) {
add(ChattingUpdateMessages(messagesList: messages));
});
// yield (state.copyWith(status: ChattingStatus.loaded, isSending: false));
}
} catch (e) {
yield (state.copyWith(status: ChattingStatus.error, error: e.message));
}
}
// Updating messagesList
Stream<ChattingState> _mapUpdateMessagesToState(
ChattingUpdateMessages event) async* {
// Adding the messagesList with the new messageList
yield (state.copyWith(
messagesList: event.messagesList, status: ChattingStatus.loaded));
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting | mirrored_repositories/flutter-wuphf-chat/lib/screens/chatting/bloc/chatting_state.dart | part of 'chatting_bloc.dart';
enum ChattingStatus {
initial,
loading,
loaded,
error,
}
class ChattingState extends Equatable {
final String userId;
final List<Message> messagesList;
final DocumentReference messagesDbRef;
final bool hasMessagedBefore;
final bool isSending;
final ChattingStatus status;
final String error;
ChattingState({
@required this.userId,
@required this.messagesList,
@required this.messagesDbRef,
@required this.hasMessagedBefore,
@required this.isSending,
@required this.status,
@required this.error,
});
factory ChattingState.initial(
{@required String userId, DocumentReference messagesDbRef}) {
return ChattingState(
userId: userId,
messagesList: [],
messagesDbRef: messagesDbRef,
hasMessagedBefore: null,
isSending: false,
status: ChattingStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
userId,
messagesList,
hasMessagedBefore,
messagesDbRef,
isSending,
status,
error,
];
ChattingState copyWith({
String userId,
List<Message> messagesList,
DocumentReference messagesDbRef,
bool hasMessagedBefore,
bool isSending,
ChattingStatus status,
String error,
}) {
return ChattingState(
userId: userId ?? this.userId,
messagesList: messagesList ?? this.messagesList,
messagesDbRef: messagesDbRef ?? this.messagesDbRef,
hasMessagedBefore: hasMessagedBefore ?? this.hasMessagedBefore,
isSending: isSending ?? this.isSending,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/view_image/view_image_screen.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class ViewImageScreenArgs {
final String imageUrl;
ViewImageScreenArgs({@required this.imageUrl});
}
class ViewImageScreen extends StatelessWidget {
static const String routeName = '/view-picture-screen';
static Route route({@required ViewImageScreenArgs args}) {
return MaterialPageRoute(
builder: (context) => ViewImageScreen(imageUrl: args.imageUrl),
);
}
const ViewImageScreen({Key key, @required this.imageUrl}) : super(key: key);
final String imageUrl;
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
physics: NeverScrollableScrollPhysics(),
slivers: [
TwoTextAppBar(title: 'View Image', subtitle: 'Pinch to zoom'),
SliverFillRemaining(
child: InteractiveViewer(
minScale: 0.5,
maxScale: 3,
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.fitWidth,
placeholder: (context, url) => Container(color: Colors.grey),
errorWidget: (context, url, error) =>
Container(color: Colors.grey),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/nav/bottom_nav_bar.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/config/configs.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
import 'package:wuphf_chat/screens/chats/bloc/chats_bloc.dart';
import 'package:wuphf_chat/screens/groups/bloc/groups_bloc.dart';
import 'package:wuphf_chat/screens/screens.dart';
import 'package:wuphf_chat/screens/users/bloc/users_bloc.dart';
class BottomNavBarScreen extends StatefulWidget {
static const String routeName = '/nav-screen';
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => BottomNavBarScreen(),
);
}
BottomNavBarScreen({Key key}) : super(key: key);
@override
_BottomNavBarScreenState createState() => _BottomNavBarScreenState();
}
class _BottomNavBarScreenState extends State<BottomNavBarScreen> {
int _selectedIndex = 1;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
List<Widget> _screens = [
BlocProvider<UsersBloc>(
create: (context) => UsersBloc(
authBloc: context.read<AuthBloc>(),
userRepository: context.read<UserRepository>(),
)..add(UsersFetchUser()),
child: UsersScreen(),
),
BlocProvider<ChatsBloc>(
create: (context) => ChatsBloc(
messagesRepository: context.read<MessagesRepository>(),
),
child: ChatsScreen(),
),
BlocProvider<GroupsBloc>(
create: (context) => GroupsBloc(
groupsRepository: context.read<GroupsRepository>(),
),
child: GroupsScreen(),
),
BlocProvider<LiveUserBloc>(
create: (context) => LiveUserBloc(
userRepository: context.read<UserRepository>(),
userId: context.read<AuthBloc>().state.user.uid,
),
child: UserProfileScreen(),
),
];
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
body: _screens.elementAt(_selectedIndex),
bottomNavigationBar: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.vertical(
top: Radius.circular(ThemeConfig.borderRadius),
),
boxShadow: [
BoxShadow(
offset: Offset(0, -2),
blurRadius: 4.0,
color: Theme.of(context).accentColor.withOpacity(0.2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.vertical(
top: Radius.circular(ThemeConfig.borderRadius),
),
child: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
items: [
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.users), label: 'Contacts'),
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.solidComment),
label: 'Chats'),
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.solidComments),
label: 'Groups'),
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.solidUserCircle),
label: 'Profile'),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group/create_group_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
import 'package:wuphf_chat/screens/create_group/widgets/group_name_widget.dart';
import 'package:wuphf_chat/screens/create_group/widgets/participants_widget.dart';
import 'package:wuphf_chat/screens/edit_profile/widgets/widgets.dart';
import 'cubit/creategroup_cubit.dart';
class CreateGroupScreenArgs {
final List<User> participants;
CreateGroupScreenArgs({@required this.participants});
}
class CreateGroupScreen extends StatefulWidget {
static const String routeName = '/create-group-screen';
static Route route({@required CreateGroupScreenArgs args}) {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => BlocProvider(
create: (context) => CreateGroupCubit(
groupsRepository: context.read<GroupsRepository>(),
storageRepository: context.read<StorageRepository>(),
participants: args.participants,
),
child: CreateGroupScreen(),
),
);
}
const CreateGroupScreen({Key key}) : super(key: key);
@override
_CreateGroupScreenState createState() => _CreateGroupScreenState();
}
class _CreateGroupScreenState extends State<CreateGroupScreen> {
final _formKey = GlobalKey<FormState>();
void _createGroup() {
if (context.read<CreateGroupCubit>().state.status ==
CreateGroupStatus.submitting) {
return;
}
if (!_formKey.currentState.validate()) {
return;
}
context.read<CreateGroupCubit>().submitForm();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
TwoTextAppBar(title: 'Create Group', subtitle: 'Edit Group Details'),
BlocConsumer<CreateGroupCubit, CreateGroupState>(
listener: (context, state) {
if (state.status == CreateGroupStatus.error) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(content: Text('${state.error}')),
);
}
if (state.status == CreateGroupStatus.submitting) {
_formKey.currentState.deactivate();
}
if (state.status == CreateGroupStatus.success) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(content: Text('Group Created!')),
);
Navigator.of(context).pop();
}
},
builder: (context, state) {
return SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ChangeProfilePicture(
label: 'Group Image',
imageUrl: state.groupImageUrl,
onChanged: context
.read<CreateGroupCubit>()
.groupImageChanged,
),
SizedBox(height: 16.0),
GroupNameWidget(
onChanged:
context.read<CreateGroupCubit>().groupNameChanged,
),
SizedBox(height: 16.0),
CustomElevatedButton(
onTap: state.status == CreateGroupStatus.submitting
? null
: () {
_createGroup();
},
titleColor:
state.status == CreateGroupStatus.submitting
? Colors.grey
: Theme.of(context).primaryColor,
title: state.status == CreateGroupStatus.submitting
? 'Creating...'
: 'Create Group',
buttonColor: Colors.white,
icon: state.status == CreateGroupStatus.submitting
? FontAwesomeIcons.spinner
: FontAwesomeIcons.folderPlus,
size: Size(
MediaQuery.of(context).size.width * 0.6, 50.0),
),
SizedBox(height: 16.0),
ParticipantsWidget(participants: state.participants),
],
),
),
),
);
},
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group | mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group/widgets/group_name_widget.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class GroupNameWidget extends StatelessWidget {
final String initialValue;
final Function onChanged;
const GroupNameWidget({
Key key,
@required this.onChanged,
this.initialValue,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InputTitle(title: 'Group Name'),
InputTextField(
hintText: 'Buddies',
textInputType: TextInputType.name,
initialValue: initialValue,
onChanged: onChanged,
validator: (String value) {
if (value.trim().isEmpty) {
return 'Group Name cannot be empty';
}
if (value.trim().length < 3) {
return 'Group Name must be at least 3 characters';
}
return null;
},
),
],
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group | mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group/widgets/participants_widget.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/screens/screens.dart';
class ParticipantsWidget extends StatelessWidget {
final List<User> participants;
final bool showPresence;
const ParticipantsWidget(
{Key key, @required this.participants, this.showPresence = false})
: super(key: key);
@override
Widget build(BuildContext context) {
final List<UserRow> userRows = participants
.map((user) => UserRow(
imageUrl: user.profileImageUrl,
title: user.displayName,
subtitle: user.bio,
isOnline: showPresence ? user.presence : null,
onChat: () {
Navigator.of(context).pushNamed(
ChattingScreen.routeName,
arguments:
ChattingScreenArgs(userId: user.id),
);
},
onView: () {
Navigator.of(context).pushNamed(
ViewProfileScreen.routeName,
arguments:
ViewProfileScreenArgs(user: user),
);
},
))
.toList();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InputTitle(title: 'Participants'),
...userRows,
],
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group | mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group/cubit/creategroup_cubit.dart | import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
part 'creategroup_state.dart';
class CreateGroupCubit extends Cubit<CreateGroupState> {
final StorageRepository _storageRepository;
final GroupsRepository _groupsRepository;
CreateGroupCubit({
@required List<User> participants,
@required StorageRepository storageRepository,
@required GroupsRepository groupsRepository,
}) : _storageRepository = storageRepository,
_groupsRepository = groupsRepository,
super(CreateGroupState.initial(participants: participants));
void groupNameChanged(String value) {
emit(state.copyWith(groupName: value.trim()));
}
void groupImageChanged(File file) {
emit(state.copyWith(newGroupImage: file));
}
Future<String> _uploadGroupImage({@required File file}) async {
try {
final downloadUrl = await _storageRepository.uploadGroupImage(
file: file,
);
return downloadUrl;
} catch (e) {
throw Exception(e.message);
}
}
Future<void> submitForm() async {
emit(state.copyWith(status: CreateGroupStatus.submitting));
try {
if (state.newGroupImage != null) {
final newGroupDPImageUrl =
await _uploadGroupImage(file: state.newGroupImage);
emit(state.copyWith(groupImageUrl: newGroupDPImageUrl));
}
final List<String> participantIds =
state.participants.map((user) => user.id).toList();
final groupDbID = await _groupsRepository.createGroup(
groupName: state.groupName,
groupImageUrl: state.groupImageUrl,
participants: participantIds,
);
emit(state.copyWith(status: CreateGroupStatus.success));
} catch (e) {
emit(state.copyWith(status: CreateGroupStatus.error, error: e.message));
}
}
void reset() {
// Default Image and Participants are not reset
emit(state.copyWith(
status: CreateGroupStatus.initial,
groupName: '',
newGroupImage: null,
error: '',
));
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group | mirrored_repositories/flutter-wuphf-chat/lib/screens/create_group/cubit/creategroup_state.dart | part of 'creategroup_cubit.dart';
enum CreateGroupStatus {
initial,
submitting,
success,
error,
}
class CreateGroupState extends Equatable {
final String groupName;
final String groupImageUrl;
final File newGroupImage;
final List<User> participants;
final CreateGroupStatus status;
final String error;
const CreateGroupState({
@required this.groupName,
@required this.groupImageUrl,
@required this.newGroupImage,
@required this.participants,
@required this.status,
@required this.error,
});
factory CreateGroupState.initial({@required List<User> participants}) {
return CreateGroupState(
groupName: '',
groupImageUrl:
'https://firebasestorage.googleapis.com/v0/b/wuphf-chat-flutter.appspot.com/o/images%2FgroupPictures%2FdefaultGroupDp.png?alt=media&token=8cd72c91-ea44-478b-98a1-555150eb2586',
newGroupImage: null,
participants: participants,
status: CreateGroupStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
groupName,
groupImageUrl,
newGroupImage,
participants,
status,
error,
];
CreateGroupState copyWith({
String groupName,
String groupImageUrl,
File newGroupImage,
List<User> participants,
CreateGroupStatus status,
String error,
}) {
return CreateGroupState(
groupName: groupName ?? this.groupName,
groupImageUrl: groupImageUrl ?? this.groupImageUrl,
newGroupImage: newGroupImage ?? this.newGroupImage,
participants: participants ?? this.participants,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details/app_details_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/screens/app_details/bloc/appdetails_bloc.dart';
import 'package:wuphf_chat/screens/dev_details/widgets/devlink.dart';
import 'package:wuphf_chat/screens/view_profile/widgets/profile_picture.dart';
class AppDetailsScreen extends StatelessWidget {
static const String routeName = '/app-details-screen';
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => BlocProvider<AppDetailsBloc>(
create: (context) => AppDetailsBloc(),
child: AppDetailsScreen(),
),
);
}
const AppDetailsScreen({Key key}) : super(key: key);
Future<void> _launchUrl(String url) async {
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: false,
);
} else {
//* Preparing For Release
// print('Could not launch $url');
}
}
@override
Widget build(BuildContext context) {
return BlocBuilder<AppDetailsBloc, AppDetailsState>(
builder: (context, state) {
if (state.status == AppDetailsStatus.loaded) {
return Scaffold(
body: CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: [
TwoTextAppBar(
title: 'App Details',
subtitle: 'Version: ${state.version}'),
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(16.0, 32.0, 16.0, 0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePictureWidget(
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/wuphf-chat-flutter.appspot.com/o/images%2Ficon%2Fplay_store_icon.png?alt=media&token=88c9b009-699a-4bcc-87d9-e0afef31711e',
isClipped: false,
),
SizedBox(height: 32.0),
Text('${state.appName}',
style: Theme.of(context).textTheme.headline4),
Text(
'${state.packageName}',
style: Theme.of(context).textTheme.subtitle2,
),
SizedBox(height: 16.0),
Text(
'Made with ❤ using Flutter',
style: Theme.of(context).textTheme.subtitle1,
),
SizedBox(height: 16.0),
DevLink(
onPressed: () {
_launchUrl(
'https://github.com/ankanSikdar/flutter-wuphf-chat');
},
icon: FontAwesomeIcons.github,
label: 'Source Code'),
DevLink(
onPressed: () {
_launchUrl(
'https://wuphf-chat-privacy-policy.web.app/');
},
icon: FontAwesomeIcons.fileAlt,
label: 'Privacy Policy'),
Row(
children: [
InputTitle(title: 'Wuphf Meaning?'),
],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: Text(
'Any Office (American Sitcom) Fans? You must have already figured it out.\nFor the rest, \'Wuphf\' (pronounced \'woof\') is the name of the website developed by a character in the show as a revolutionary communication tool. Instead of getting a text or call, or message, the service purportedly sends a message to friends on all their channels, facebook, sms and twitter. It even prints out a \'Wuphf\' on the nearest printer. So while watching that episode I thought of creating a chat app named Wuphf one day',
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.justify,
),
),
SizedBox(height: 16.0),
Row(
children: [
InputTitle(title: 'Disclaimer'),
],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: Text(
'Please don\'t consider using the app as your primary chatting app. This app is purely made for learning purposes. Please treat it as so.',
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.justify,
),
),
SizedBox(height: 32.0),
],
),
),
),
],
),
);
}
if (state.status == AppDetailsStatus.error) {
return Center(
child: Text('Something went wrong!'),
);
}
return LoadingIndicator();
},
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details | mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details/bloc/appdetails_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:package_info/package_info.dart';
part 'appdetails_event.dart';
part 'appdetails_state.dart';
class AppDetailsBloc extends Bloc<AppDetailsEvent, AppDetailsState> {
PackageInfo _packageInfo;
AppDetailsBloc() : super(AppDetailsState.initial()) {
add(LoadAppDetails());
}
@override
Stream<AppDetailsState> mapEventToState(
AppDetailsEvent event,
) async* {
if (event is LoadAppDetails) {
yield* _mapLoadAppDetailsToState();
}
}
Stream<AppDetailsState> _mapLoadAppDetailsToState() async* {
yield state.copyWith(status: AppDetailsStatus.loading);
try {
_packageInfo = await PackageInfo.fromPlatform();
yield state.copyWith(
status: AppDetailsStatus.loaded,
appName: _packageInfo.appName,
packageName: _packageInfo.packageName,
version: _packageInfo.version,
buildNumber: _packageInfo.buildNumber,
);
} catch (e) {
yield state.copyWith(status: AppDetailsStatus.error, error: e);
}
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details | mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details/bloc/appdetails_state.dart | part of 'appdetails_bloc.dart';
enum AppDetailsStatus {
initial,
loading,
loaded,
error,
}
class AppDetailsState extends Equatable {
final String appName;
final String packageName;
final String version;
final String buildNumber;
final AppDetailsStatus status;
final String error;
AppDetailsState({
@required this.appName,
@required this.packageName,
@required this.version,
@required this.buildNumber,
@required this.status,
@required this.error,
});
factory AppDetailsState.initial() {
return AppDetailsState(
appName: '',
packageName: '',
version: '',
buildNumber: '',
status: AppDetailsStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
appName,
packageName,
version,
buildNumber,
status,
error,
];
AppDetailsState copyWith({
String appName,
String packageName,
String version,
String buildNumber,
AppDetailsStatus status,
String error,
}) {
return AppDetailsState(
appName: appName ?? this.appName,
packageName: packageName ?? this.packageName,
version: version ?? this.version,
buildNumber: buildNumber ?? this.buildNumber,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details | mirrored_repositories/flutter-wuphf-chat/lib/screens/app_details/bloc/appdetails_event.dart | part of 'appdetails_bloc.dart';
abstract class AppDetailsEvent extends Equatable {
const AppDetailsEvent();
@override
List<Object> get props => [];
}
class LoadAppDetails extends AppDetailsEvent {}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/dev_details/dev_details_screen.dart | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/global_widgets/two_text_app_bar.dart';
import 'package:wuphf_chat/screens/dev_details/widgets/devlink.dart';
import 'package:wuphf_chat/screens/view_profile/widgets/profile_picture.dart';
class DevDetailsScreen extends StatelessWidget {
static const routeName = '/dev-details-screen';
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => DevDetailsScreen(),
);
}
const DevDetailsScreen({Key key}) : super(key: key);
Future<void> _launchUrl(String url) async {
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: false,
);
} else {
//* Preparing For Release
// print('Could not launch $url');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: [
TwoTextAppBar(
title: 'Developer Details',
subtitle: '[email protected]',
),
SliverPadding(
padding: EdgeInsets.all(16.0),
sliver: SliverToBoxAdapter(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ProfilePictureWidget(
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/wuphf-chat-flutter.appspot.com/o/images%2Ficon%2Fankan.jpeg?alt=media&token=469db95c-52b2-4be0-a5d7-4382cf713c33',
),
SizedBox(height: 16.0),
Text('Ankan Sikdar',
style: Theme.of(context).textTheme.headline4),
SizedBox(height: 16.0),
Container(
width: double.infinity,
child: InputTitle(title: 'About Me'),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: Text(
'Hello There! First of all I am very grateful to you for using my app. A little about myself. I was born in 1999 and I am an Engineer in Information Technology (Graduated in 2021) from Heritage Institute of Technology, Kolkata. I primarily spend most of my time learning and developing in Flutter. And I love sunsets, stargazing and solitude. Thats all I can think of for now. 😅',
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.justify,
),
),
SizedBox(height: 16.0),
Row(
children: [
InputTitle(title: 'My Links'),
],
),
SizedBox(height: 8.0),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: Text(
'Feel free to contact me regarding a bug, or any criticism that you might have. Or maybe just to talk about coding or life in general.',
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.justify,
),
),
DevLink(
icon: FontAwesomeIcons.github,
label: 'GitHub',
onPressed: () {
_launchUrl('https://github.com/ankanSikdar');
},
),
DevLink(
icon: FontAwesomeIcons.linkedin,
label: 'LinkedIn',
onPressed: () {
_launchUrl('https://www.linkedin.com/in/ankansikdar/');
},
),
DevLink(
icon: FontAwesomeIcons.facebook,
label: 'Facebook',
onPressed: () {
_launchUrl('https://www.facebook.com/ankanSikdar/');
},
),
DevLink(
icon: FontAwesomeIcons.twitter,
label: 'Twitter',
onPressed: () {
_launchUrl('https://twitter.com/ankan_sikdar');
},
),
DevLink(
icon: FontAwesomeIcons.instagram,
label: 'Instagram',
onPressed: () {
_launchUrl('https://www.instagram.com/ankan_sikdar/');
},
),
DevLink(
icon: FontAwesomeIcons.solidEnvelope,
label: 'Send Email',
onPressed: () {
_launchUrl(
'mailto:[email protected]?subject=Reason%20you%20are%20contacting%20me&body=Hello%20Ankan%21');
},
),
],
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/dev_details | mirrored_repositories/flutter-wuphf-chat/lib/screens/dev_details/widgets/devlink.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class DevLink extends StatelessWidget {
final Function onPressed;
final IconData icon;
final String label;
const DevLink({
Key key,
@required this.onPressed,
@required this.icon,
@required this.label,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: CustomElevatedButton(
icon: icon,
buttonColor: Colors.white,
titleColor: Theme.of(context).primaryColor,
title: label,
onTap: onPressed,
size: Size(MediaQuery.of(context).size.width * 0.6, 50.0),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/user_profile_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/screens/screens.dart';
import 'package:wuphf_chat/screens/user_profile/widgets/widgets.dart';
class UserProfileScreen extends StatelessWidget {
static const String routeName = '/user-profile-screen';
const UserProfileScreen({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<LiveUserBloc, LiveUserState>(
builder: (context, state) {
if (state.status == LiveUserStatus.loaded) {
return Scaffold(
body: NestedScrollView(
headerSliverBuilder: (context, innerBoxIsScrolled) {
return [
UserAppBar(
displayName: state.user.displayName,
profileImageUrl: state.user.profileImageUrl,
email: state.user.email,
),
];
},
body: ListView(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(16.0),
children: [
UserHeader(
title: 'About',
),
AboutContainer(
about: state.user.bio,
),
UserHeader(
title: 'Settings',
),
SettingsWidget(
name: 'Edit Profile',
icon: Icons.edit,
color: Colors.deepOrange[200],
onTap: () {
Navigator.of(context).pushNamed(
EditProfileScreen.routeName,
arguments: EditProfileArgs(user: state.user),
);
},
),
SettingsWidget(
name: 'Developer Details',
icon: FontAwesomeIcons.userSecret,
color: Colors.blueAccent[200],
onTap: () {
Navigator.of(context).pushNamed(
DevDetailsScreen.routeName,
);
},
),
SettingsWidget(
name: 'App Details',
icon: Icons.info_outline,
color: Colors.deepPurple[200],
onTap: () {
Navigator.of(context)
.pushNamed(AppDetailsScreen.routeName);
},
),
],
),
),
floatingActionButtonLocation:
FloatingActionButtonLocation.endDocked,
floatingActionButton: SignOutButton(),
);
}
if (state.status == LiveUserStatus.error) {
return Center(
child: Text(state.error),
);
}
return Center(child: LoadingIndicator());
},
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/settings_widget.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
class SettingsWidget extends StatelessWidget {
final Function onTap;
final IconData icon;
final String name;
final Color color;
const SettingsWidget({
Key key,
@required this.onTap,
@required this.icon,
@required this.name,
@required this.color,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
splashColor: color,
child: Container(
padding: EdgeInsets.all(4.0),
margin: EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: [
Container(
padding: EdgeInsets.all(8.0),
child: Icon(icon, size: 32),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(ThemeConfig.borderRadius),
),
),
SizedBox(width: 8.0),
Expanded(
child: Text(
name,
style: Theme.of(context).textTheme.button,
),
),
Icon(Icons.navigate_next),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/signout_button.dart | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class SignOutButton extends StatelessWidget {
const SignOutButton({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 16.0),
child: CustomElevatedButton(
onTap: () {
context.read<AuthBloc>().add(AuthUserLogOut());
},
icon: FontAwesomeIcons.signOutAlt,
title: 'Sign Out',
titleColor: Colors.grey[600],
buttonColor: Colors.white,
size: Size(MediaQuery.of(context).size.width * 0.6, 50.0),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/widgets.dart | export 'user_app_bar.dart';
export 'user_header.dart';
export 'about_container.dart';
export 'settings_widget.dart';
export 'signout_button.dart';
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/user_header.dart | import 'package:flutter/material.dart';
class UserHeader extends StatelessWidget {
final String title;
const UserHeader({
Key key,
@required this.title,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text(
title,
style: Theme.of(context)
.textTheme
.headline4
.copyWith(fontWeight: FontWeight.w600),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/about_container.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
class AboutContainer extends StatelessWidget {
final String about;
const AboutContainer({Key key, @required this.about}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: 200,
margin: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 16.0),
padding: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(ThemeConfig.borderRadius)),
child: Text(
about.isEmpty ? 'No About' : about,
style: Theme.of(context).textTheme.bodyText1,
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/user_profile/widgets/user_app_bar.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/screens/screens.dart';
class UserAppBar extends StatelessWidget {
final String email;
final String displayName;
final String profileImageUrl;
const UserAppBar({
Key key,
@required this.email,
@required this.displayName,
@required this.profileImageUrl,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SliverAppBar(
elevation: 2.0,
shadowColor: Colors.grey[500],
backgroundColor: Colors.white,
toolbarHeight: 100,
floating: true,
pinned: true,
forceElevated: true,
automaticallyImplyLeading: false,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(ThemeConfig.borderRadius),
),
),
title: Container(
child: Row(
children: [
GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(
ViewImageScreen.routeName,
arguments: ViewImageScreenArgs(imageUrl: profileImageUrl),
);
},
child: ProfilePicture(
imageUrl: profileImageUrl,
),
),
SizedBox(width: 16.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
displayName,
style: Theme.of(context).textTheme.headline5,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 8.0),
Text(
email,
style: Theme.of(context).textTheme.subtitle1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/edit_profile_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
import 'package:wuphf_chat/screens/edit_profile/cubit/editprofile_cubit.dart';
import 'package:wuphf_chat/screens/edit_profile/widgets/widgets.dart';
class EditProfileArgs {
final User user;
EditProfileArgs({@required this.user});
}
class EditProfileScreen extends StatefulWidget {
static const String routeName = '/edit-profile-screen';
static Route route({@required EditProfileArgs args}) {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => BlocProvider<EditProfileCubit>(
create: (context) => EditProfileCubit(
user: args.user,
authRepository: context.read<AuthRepository>(),
userRepository: context.read<UserRepository>(),
storageRepository: context.read<StorageRepository>(),
),
child: EditProfileScreen(),
),
);
}
const EditProfileScreen({Key key}) : super(key: key);
@override
_EditProfileScreenState createState() => _EditProfileScreenState();
}
class _EditProfileScreenState extends State<EditProfileScreen> {
final _formkey = GlobalKey<FormState>();
void _submitForm() {
if (context.read<EditProfileCubit>().state.status ==
EditProfileStatus.submitting) {
return;
}
if (!_formkey.currentState.validate()) {
return;
}
context.read<EditProfileCubit>().submitForm();
}
@override
Widget build(BuildContext context) {
return BlocConsumer<EditProfileCubit, EditProfileState>(
listener: (context, state) {
if (state.status == EditProfileStatus.error) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(content: Text('${state.error}')),
);
context.read<EditProfileCubit>().reset();
}
if (state.status == EditProfileStatus.submitting) {
_formkey.currentState.deactivate();
}
if (state.status == EditProfileStatus.success) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(content: Text('Profile Updated')),
);
}
},
builder: (context, state) {
return Scaffold(
body: CustomScrollView(slivers: [
TwoTextAppBar(
title: 'Edit Profile', subtitle: 'Edit your details here'),
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 100.0),
child: Form(
key: _formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ChangeProfilePicture(
label: 'Profile Image',
imageUrl: state.profileImageUrl,
onChanged: (File file) {
context
.read<EditProfileCubit>()
.profileImageChanged(file);
},
),
SizedBox(height: 24.0),
EmailWidget(
initialValue: state.email,
onChanged:
context.read<EditProfileCubit>().emailChanged,
),
SizedBox(height: 16.0),
DisplayNameWidget(
initialValue: state.displayName,
onChanged:
context.read<EditProfileCubit>().displayNameChanged,
),
SizedBox(height: 16.0),
AboutWidget(
initialValue: state.bio,
onChanged: context.read<EditProfileCubit>().bioChanged,
),
],
),
),
),
),
]),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerDocked,
floatingActionButton: CustomElevatedButton(
onTap: state.status == EditProfileStatus.submitting
? null
: () {
_submitForm();
},
titleColor: state.status == EditProfileStatus.submitting
? Colors.grey
: Theme.of(context).primaryColor,
title: state.status == EditProfileStatus.submitting
? 'Submitting...'
: 'Submit',
buttonColor: Colors.white,
icon: state.status == EditProfileStatus.submitting
? FontAwesomeIcons.spinner
: FontAwesomeIcons.save,
size: Size(MediaQuery.of(context).size.width * 0.6, 50.0),
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/widgets/change_profile_picture.dart | import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:wuphf_chat/config/configs.dart';
class ChangeProfilePicture extends StatefulWidget {
ChangeProfilePicture(
{Key key,
@required this.imageUrl,
@required this.onChanged,
@required this.label})
: super(key: key);
final String imageUrl;
final Function onChanged;
final String label;
@override
_ChangeProfilePictureState createState() => _ChangeProfilePictureState();
}
class _ChangeProfilePictureState extends State<ChangeProfilePicture> {
final _picker = ImagePicker();
File file;
Future<void> _pickImage() async {
final pickedFile = await _picker.getImage(
source: ImageSource.gallery,
imageQuality: 50,
);
if (pickedFile != null) {
final croppedFile = await ImageCropper.cropImage(
sourcePath: pickedFile.path,
aspectRatioPresets: [CropAspectRatioPreset.square],
androidUiSettings: AndroidUiSettings(
toolbarTitle: widget.label,
toolbarColor: Colors.white,
backgroundColor: Colors.white,
activeControlsWidgetColor: Theme.of(context).primaryColor,
toolbarWidgetColor: Theme.of(context).primaryColor,
initAspectRatio: CropAspectRatioPreset.square,
),
iosUiSettings: IOSUiSettings(
title: 'Profile Picture',
),
);
if (croppedFile != null) {
widget.onChanged(croppedFile);
setState(() {
file = croppedFile;
});
}
}
}
@override
Widget build(BuildContext context) {
return Container(
height: 250,
width: 250,
// margin:
// EdgeInsets.only(left: MediaQuery.of(context).size.width * 0.160),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(ThemeConfig.dpRadius),
color: Colors.grey[200],
),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(ThemeConfig.dpRadius),
child: file == null
? CachedNetworkImage(
imageUrl: widget.imageUrl,
fit: BoxFit.cover,
placeholder: (context, url) =>
Container(color: Colors.grey),
errorWidget: (context, url, error) =>
Container(color: Colors.grey),
)
: Container(
child: Image.file(
file,
fit: BoxFit.cover,
),
),
),
Positioned(
bottom: 8.0,
right: 8.0,
child: GestureDetector(
onTap: () async {
await _pickImage();
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
offset: Offset(0.0, 1.0), //(x,y)
blurRadius: 4.0,
)
]),
padding: EdgeInsets.all(12.0),
child: FaIcon(
FontAwesomeIcons.image,
size: 28.0,
color: Theme.of(context).primaryColor,
),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/widgets/widgets.dart | export 'change_profile_picture.dart';
export 'about_widget.dart';
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/widgets/about_widget.dart | import 'package:flutter/material.dart';
import 'package:wuphf_chat/config/configs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class AboutWidget extends StatelessWidget {
final String initialValue;
final Function onChanged;
const AboutWidget({
Key key,
@required this.onChanged,
this.initialValue,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InputTitle(title: 'About'),
TextFormField(
decoration: InputDecoration(
fillColor: Colors.grey[200],
filled: true,
hintText: 'Write something about yourself',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(ThemeConfig.borderRadius),
borderSide: BorderSide.none,
),
contentPadding: EdgeInsets.all(12.0),
errorStyle: Theme.of(context).textTheme.bodyText2.apply(
color: Theme.of(context).errorColor,
),
),
initialValue: initialValue,
minLines: 1,
maxLines: 4,
maxLength: 100,
style: Theme.of(context).textTheme.bodyText1,
keyboardType: TextInputType.multiline,
onChanged: onChanged,
validator: (String value) {
if (value.trim().length == 0) {
return 'About should not be empty';
}
return null;
},
),
],
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/cubit/editprofile_cubit.dart | import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
part 'editprofile_state.dart';
class EditProfileCubit extends Cubit<EditProfileState> {
final User _user;
final UserRepository _userRepository;
final AuthRepository _authRepository;
final StorageRepository _storageRepository;
EditProfileCubit({
@required User user,
@required UserRepository userRepository,
@required AuthRepository authRepository,
@required StorageRepository storageRepository,
}) : _userRepository = userRepository,
_user = user,
_authRepository = authRepository,
_storageRepository = storageRepository,
super(EditProfileState.initial()) {
emit(state.copyWith(
displayName: _user.displayName,
email: _user.email,
bio: _user.bio,
profileImageUrl: _user.profileImageUrl,
));
}
Future<void> emailChanged(String value) async {
emit(state.copyWith(email: value.trim()));
}
Future<void> displayNameChanged(String value) async {
emit(state.copyWith(displayName: value.trim()));
}
Future<void> bioChanged(String value) async {
emit(state.copyWith(bio: value.trim()));
}
Future<void> profileImageChanged(File file) async {
emit(state.copyWith(newProfileImage: file));
}
Future<void> _updateEmailAndDisplayNameIfChangedInAuthRepo() async {
try {
if (_user.email != state.email) {
await _authRepository.updateEmail(email: state.email);
}
if (_user.displayName != state.displayName) {
await _authRepository.updateDisplayName(displayName: state.displayName);
}
} catch (e) {
throw Exception(e.message);
}
}
Future<String> _uploadProfilePicture({@required File file}) async {
try {
final downloadUrl = await _storageRepository.uploadProfileImage(
userId: _user.id,
file: file,
);
return downloadUrl;
} catch (e) {
throw Exception(e.message);
}
}
Future<void> submitForm() async {
emit(state.copyWith(status: EditProfileStatus.submitting));
try {
await _updateEmailAndDisplayNameIfChangedInAuthRepo();
if (state.newProfileImage != null) {
final newProfileImageUrl =
await _uploadProfilePicture(file: state.newProfileImage);
emit(state.copyWith(profileImageUrl: newProfileImageUrl));
}
await _userRepository.updateUser(
user: User(
id: _user.id,
displayName: state.displayName,
email: state.email,
profileImageUrl: state.profileImageUrl,
bio: state.bio,
));
emit(state.copyWith(status: EditProfileStatus.success));
} catch (e) {
emit(state.copyWith(status: EditProfileStatus.error, error: e.message));
}
}
void reset() {
emit(state.copyWith(
status: EditProfileStatus.initial,
error: '',
));
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile | mirrored_repositories/flutter-wuphf-chat/lib/screens/edit_profile/cubit/editprofile_state.dart | part of 'editprofile_cubit.dart';
enum EditProfileStatus {
initial,
submitting,
success,
error,
}
class EditProfileState extends Equatable {
final String displayName;
final String email;
final String bio;
final String profileImageUrl;
final File newProfileImage;
final EditProfileStatus status;
final String error;
const EditProfileState({
@required this.displayName,
@required this.email,
@required this.bio,
@required this.profileImageUrl,
@required this.newProfileImage,
@required this.status,
@required this.error,
});
factory EditProfileState.initial() {
return EditProfileState(
displayName: '',
email: '',
bio: '',
profileImageUrl: '',
newProfileImage: null,
status: EditProfileStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
displayName,
email,
bio,
profileImageUrl,
newProfileImage,
status,
error,
];
EditProfileState copyWith({
String displayName,
String email,
String bio,
String profileImageUrl,
File newProfileImage,
EditProfileStatus status,
String error,
}) {
return EditProfileState(
displayName: displayName ?? this.displayName,
email: email ?? this.email,
bio: bio ?? this.bio,
profileImageUrl: profileImageUrl ?? this.profileImageUrl,
newProfileImage: newProfileImage ?? this.newProfileImage,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/splash/splash_screen.dart | import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/screens/screens.dart';
class SplashScreen extends StatefulWidget {
static const String routeName = '/splash';
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => SplashScreen(),
);
}
const SplashScreen({Key key}) : super(key: key);
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen>
with WidgetsBindingObserver {
RemoteMessage initialMessage;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
setupInitialMessage();
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
final data = message.data;
handleNotification(data: data);
});
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
context.read<AuthBloc>().add(AppResumedUpdatePresence());
break;
case AppLifecycleState.inactive:
// Do nothing
break;
case AppLifecycleState.paused:
context.read<AuthBloc>().add(AppInBackgroundUpdatePresence());
break;
case AppLifecycleState.detached:
// Already Handled
break;
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
Future<void> setupInitialMessage() async {
// Get any messages which caused the application to open from
// a terminated state.
initialMessage = await FirebaseMessaging.instance.getInitialMessage();
}
void handleNotification({@required Map<String, dynamic> data}) {
if (data['type'] == 'new-chat') {
final userId = data['userId'];
Navigator.of(context).pushNamed(ChattingScreen.routeName,
arguments: ChattingScreenArgs(userId: userId));
} else if (data['type'] == 'new-group') {
final groupDbId = data['groupDbId'];
Navigator.of(context).pushNamed(GroupChattingScreen.routeName,
arguments: GroupChattingScreenArgs(groupId: groupDbId));
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: BlocListener<AuthBloc, AuthState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
// No user is found
if (state.status == AuthStatus.unauthenticated) {
return Navigator.of(context).pushNamed(SignUpScreen.routeName);
}
// User is found and user is logged in
if (state.status == AuthStatus.authenticated) {
if (initialMessage == null) {
// App opened normally
return Navigator.of(context)
.pushNamed(BottomNavBarScreen.routeName);
} else {
// App opened from terminated state by clicking notification
Navigator.of(context).pushNamed(BottomNavBarScreen.routeName);
handleNotification(data: initialMessage.data);
return null;
}
}
},
// When status is unknown
//* Status changes to unauthenticated when no user is found or to authenticated when user is found
child: Scaffold(
body: Center(
child: LoadingIndicator(),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/groups/groups_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/screens/group_chatting/group_chatting.dart';
import 'package:wuphf_chat/screens/groups/bloc/groups_bloc.dart';
import 'package:wuphf_chat/helper/time_helper.dart';
import 'package:wuphf_chat/screens/screens.dart';
class GroupsScreen extends StatefulWidget {
static const String routeName = '/groups-screen';
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => GroupsScreen(),
);
}
const GroupsScreen({Key key}) : super(key: key);
@override
_GroupsScreenState createState() => _GroupsScreenState();
}
class _GroupsScreenState extends State<GroupsScreen> {
TextEditingController _textEditingController;
@override
void initState() {
super.initState();
_textEditingController = TextEditingController();
}
String createLastMessage({@required Message message, @required bool addYou}) {
String text = '';
if (addYou) {
text = 'You: ';
}
if (message.imageUrl != null && message.imageUrl.trim().isNotEmpty) {
text = text + '📷 ' + message.text;
return text;
}
return text + message.text;
}
void _search(String name) {
context.read<GroupsBloc>().add(SearchGroups(name: name));
}
void _stopSearch() {
context.read<GroupsBloc>().add(StopSearch());
_textEditingController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<GroupsBloc, GroupsState>(
builder: (context, state) {
if (state.status == GroupsStatus.loaded ||
state.status == GroupsStatus.searching) {
List<Group> groups = state.status == GroupsStatus.searching
? state.searchList
: state.groupsList;
return CustomScrollView(
physics: groups.length == 0
? NeverScrollableScrollPhysics()
: BouncingScrollPhysics(),
slivers: [
SearchSliverAppBar(
title: 'Groups',
textEditingController: _textEditingController,
suffixActive: state.status == GroupsStatus.searching,
search: _search,
stopSearch: _stopSearch,
searchTitle: 'groups',
),
SliverPadding(
padding: EdgeInsets.fromLTRB(16.0, 8.0, 8.0, 0.0),
sliver: state.groupsList.length == 0
? SliverToBoxAdapter(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
'assets/images/group_chat.png',
height: MediaQuery.of(context).size.width * 0.6,
width: MediaQuery.of(context).size.width * 0.6,
fit: BoxFit.fitHeight,
),
SizedBox(height: 16.0),
Text('No Group Chats To Show'),
],
),
)
: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final group = groups[index];
final addYou =
context.read<AuthBloc>().state.user.uid ==
group.lastMessage.sentBy;
final text = createLastMessage(
message: group.lastMessage, addYou: addYou);
return UserRow(
title: group.groupName,
subtitle: text,
imageUrl: group.groupImage,
date: group.lastMessage.sentAt.forLastMessage(),
onChat: () {
Navigator.of(context).pushNamed(
GroupChattingScreen.routeName,
arguments: GroupChattingScreenArgs(
groupId: group.groupId),
);
},
onView: () {
Navigator.of(context).pushNamed(
ViewGroupScreen.routeName,
arguments: ViewGroupScreenArgs(
groupId: group.groupId));
},
);
},
childCount: groups.length,
),
),
),
],
);
}
if (state.status == GroupsStatus.error) {
return Center(
child: Text('Something Went Wrong!'),
);
}
return Center(
child: LoadingIndicator(),
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/groups | mirrored_repositories/flutter-wuphf-chat/lib/screens/groups/bloc/groups_state.dart | part of 'groups_bloc.dart';
enum GroupsStatus {
initial,
loading,
loaded,
searching,
error,
}
class GroupsState extends Equatable {
final List<Group> groupsList;
final List<Group> searchList;
final GroupsStatus status;
final String error;
const GroupsState({
@required this.groupsList,
@required this.searchList,
@required this.status,
@required this.error,
});
factory GroupsState.initial() {
return GroupsState(
groupsList: [],
searchList: [],
status: GroupsStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
groupsList,
searchList,
status,
error,
];
GroupsState copyWith({
List<Group> groupsList,
List<Group> searchList,
GroupsStatus status,
String error,
}) {
return GroupsState(
groupsList: groupsList ?? this.groupsList,
searchList: searchList ?? this.searchList,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/groups | mirrored_repositories/flutter-wuphf-chat/lib/screens/groups/bloc/groups_event.dart | part of 'groups_bloc.dart';
abstract class GroupsEvent extends Equatable {
const GroupsEvent();
@override
List<Object> get props => [];
}
class FetchGroups extends GroupsEvent {}
class UpdateGroups extends GroupsEvent {
final List<Group> groupsList;
UpdateGroups({@required this.groupsList});
@override
List<Object> get props => [groupsList];
}
class SearchGroups extends GroupsEvent {
final String name;
SearchGroups({@required this.name});
@override
List<Object> get props => [name];
}
class StopSearch extends GroupsEvent {}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/groups | mirrored_repositories/flutter-wuphf-chat/lib/screens/groups/bloc/groups_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
part 'groups_event.dart';
part 'groups_state.dart';
class GroupsBloc extends Bloc<GroupsEvent, GroupsState> {
final GroupsRepository _groupsRepository;
GroupsBloc({@required GroupsRepository groupsRepository})
: _groupsRepository = groupsRepository,
super(GroupsState.initial()) {
add(FetchGroups());
}
StreamSubscription<List<Group>> _groupsSubscription;
@override
Stream<GroupsState> mapEventToState(
GroupsEvent event,
) async* {
if (event is FetchGroups) {
yield* _mapFetchGroupsToState();
}
if (event is UpdateGroups) {
yield* _mapUpdateGroupsToState(event);
}
if (event is SearchGroups) {
yield* _mapSearchGroupsToState(event);
}
if (event is StopSearch) {
yield* _mapStopSearchToState();
}
}
Stream<GroupsState> _mapFetchGroupsToState() async* {
yield state.copyWith(status: GroupsStatus.loading);
try {
_groupsSubscription?.cancel();
_groupsSubscription =
_groupsRepository.getGroupsList().listen((groupList) {
add(UpdateGroups(groupsList: groupList));
});
} catch (e) {
yield (state.copyWith(status: GroupsStatus.error, error: e.message));
}
}
Stream<GroupsState> _mapUpdateGroupsToState(UpdateGroups event) async* {
yield state.copyWith(
groupsList: event.groupsList, status: GroupsStatus.loaded);
}
Stream<GroupsState> _mapSearchGroupsToState(SearchGroups event) async* {
List<Group> results = [];
state.groupsList.forEach((group) {
if (group.groupName.toLowerCase().contains(event.name.toLowerCase())) {
results.add(group);
}
});
yield state.copyWith(
searchList: results,
status: GroupsStatus.searching,
);
}
Stream<GroupsState> _mapStopSearchToState() async* {
yield state.copyWith(searchList: [], status: GroupsStatus.loaded);
}
@override
Future<void> close() async {
_groupsSubscription.cancel();
super.close();
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/users/users_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/screens/chatting/chatting_screen.dart';
import 'package:wuphf_chat/screens/create_group/create_group_screen.dart';
import 'package:wuphf_chat/screens/screens.dart';
import 'package:wuphf_chat/screens/users/bloc/users_bloc.dart';
import 'package:wuphf_chat/screens/users/widgets/selecting_fab.dart';
class UsersScreen extends StatefulWidget {
static const String routeName = '/users-screen';
// Dont need this since the UsersScreen is created through NavScreen
// static Route route() {
// return MaterialPageRoute(
// settings: RouteSettings(name: routeName),
// builder: (context) => UsersScreen(),
// );
// }
const UsersScreen({Key key}) : super(key: key);
@override
_UsersScreenState createState() => _UsersScreenState();
}
class _UsersScreenState extends State<UsersScreen> {
TextEditingController _textEditingController;
@override
void initState() {
super.initState();
_textEditingController = TextEditingController();
}
void _search(String name) {
context.read<UsersBloc>().add(
UsersUpdateSearchList(name: name),
);
}
void _stopSearch() {
context.read<UsersBloc>().add(UsersStopSearching());
_textEditingController.clear();
}
void _selectUser({@required User user, @required int length}) {
if (length >= 10) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Maximum 10 users can be selected!'),
),
);
return;
}
context.read<UsersBloc>().add(
UsersUpdateSelectedList(user: user),
);
}
void _stopSelecting() {
context.read<UsersBloc>().add(UsersStopSelecting());
}
void _submitGroup({@required List<User> participants}) {
Navigator.of(context).pushNamed(CreateGroupScreen.routeName,
arguments: CreateGroupScreenArgs(participants: participants));
_stopSelecting();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<UsersBloc, UsersState>(
builder: (context, state) {
if (state.status == UsersStateStatus.error) {
return Center(
child: Text(state.error),
);
}
if (state.status == UsersStateStatus.loaded ||
state.status == UsersStateStatus.searching ||
state.status == UsersStateStatus.selecting) {
final isSelecting = state.status == UsersStateStatus.selecting;
final List<User> usersList =
state.searchList.isNotEmpty ? state.searchList : state.usersList;
return Scaffold(
body: CustomScrollView(
physics: usersList.length == 0
? NeverScrollableScrollPhysics()
: BouncingScrollPhysics(),
slivers: [
SearchSliverAppBar(
title: isSelecting ? 'Create Group' : 'Users',
textEditingController: _textEditingController,
suffixActive: state.searchList.isNotEmpty,
search: _search,
stopSearch: _stopSearch,
),
SliverPadding(
padding: EdgeInsets.fromLTRB(
16.0, 8.0, 8.0, isSelecting ? 84.0 : 0.0),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final user = usersList[index];
final isSelected = state.selectedList.contains(user);
return UserRow(
isChecked: isSelected,
title: user.displayName,
subtitle: user.bio.isEmpty ? user.email : user.bio,
imageUrl: user.profileImageUrl,
isOnline: user.presence,
onChat: isSelecting
? () => _selectUser(
user: user, length: state.selectedList.length)
: () {
Navigator.of(context).pushNamed(
ChattingScreen.routeName,
arguments:
ChattingScreenArgs(userId: user.id),
);
},
onLongPress: () {
_selectUser(
user: user, length: state.selectedList.length);
},
onView: isSelecting
? () => _selectUser(
user: user, length: state.selectedList.length)
: () {
Navigator.of(context).pushNamed(
ViewProfileScreen.routeName,
arguments:
ViewProfileScreenArgs(user: user),
);
},
);
},
childCount: usersList.length,
),
),
),
],
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
floatingActionButton: isSelecting
? SelectingFAB(
onCreate: () {
_submitGroup(participants: state.selectedList);
},
onCancel: () {
_stopSelecting();
},
)
: null,
);
}
return Center(child: LoadingIndicator());
},
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/users | mirrored_repositories/flutter-wuphf-chat/lib/screens/users/widgets/selecting_fab.dart | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/config/configs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
class SelectingFAB extends StatelessWidget {
final Function onCreate;
final Function onCancel;
const SelectingFAB({
Key key,
@required this.onCreate,
@required this.onCancel,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
CustomElevatedButton(
icon: FontAwesomeIcons.folderPlus,
onTap: onCreate,
buttonColor: Colors.white,
title: 'Create a Group',
titleColor: Theme.of(context).primaryColor,
),
CustomElevatedButton(
icon: FontAwesomeIcons.times,
onTap: onCancel,
buttonColor: Colors.white,
title: 'Cancel',
titleColor: Theme.of(context).primaryColor,
),
],
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/users | mirrored_repositories/flutter-wuphf-chat/lib/screens/users/bloc/users_event.dart | part of 'users_bloc.dart';
abstract class UsersEvent extends Equatable {
const UsersEvent();
@override
List<Object> get props => [];
}
class UsersFetchUser extends UsersEvent {}
class UsersUpdateUser extends UsersEvent {
final List<User> usersList;
UsersUpdateUser({@required this.usersList});
@override
List<Object> get props => [usersList];
}
class UsersUpdateSearchList extends UsersEvent {
final String name;
UsersUpdateSearchList({this.name});
@override
List<Object> get props => [name];
}
class UsersStopSearching extends UsersEvent {}
class UsersUpdateSelectedList extends UsersEvent {
final User user;
UsersUpdateSelectedList({this.user});
@override
List<Object> get props => [user];
}
class UsersStopSelecting extends UsersEvent {}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/users | mirrored_repositories/flutter-wuphf-chat/lib/screens/users/bloc/users_state.dart | part of 'users_bloc.dart';
enum UsersStateStatus {
initial,
loading,
loaded,
searching,
selecting,
error,
}
class UsersState extends Equatable {
final List<User> usersList;
final List<User> searchList;
final List<User> selectedList;
final UsersStateStatus status;
final String error;
const UsersState({
@required this.usersList,
@required this.searchList,
@required this.selectedList,
@required this.status,
@required this.error,
});
factory UsersState.initial() {
return UsersState(
usersList: [],
searchList: [],
selectedList: [],
status: UsersStateStatus.initial,
error: '',
);
}
@override
List<Object> get props => [
usersList,
status,
searchList,
selectedList,
error,
];
UsersState copyWith({
List<User> usersList,
List<User> searchList,
List<User> selectedList,
UsersStateStatus status,
String error,
}) {
return UsersState(
usersList: usersList ?? this.usersList,
searchList: searchList ?? this.searchList,
selectedList: selectedList ?? this.selectedList,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/users | mirrored_repositories/flutter-wuphf-chat/lib/screens/users/bloc/users_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/user/user_repository.dart';
part 'users_event.dart';
part 'users_state.dart';
class UsersBloc extends Bloc<UsersEvent, UsersState> {
final AuthBloc _authBloc;
final UserRepository _userRepository;
StreamSubscription _usersSubscription;
UsersBloc(
{@required AuthBloc authBloc, @required UserRepository userRepository})
: _authBloc = authBloc,
_userRepository = userRepository,
super(UsersState.initial());
@override
Stream<UsersState> mapEventToState(
UsersEvent event,
) async* {
if (event is UsersFetchUser) {
yield* _mapUsersFetchUserToState();
}
if (event is UsersUpdateUser) {
yield* _mapUsersUpdateUserToState(event);
}
if (event is UsersUpdateSearchList) {
yield* _mapUsersUpdateSearchListToState(event);
}
if (event is UsersStopSearching) {
yield* _mapUsersStopSearchingToState();
}
if (event is UsersUpdateSelectedList) {
yield* _mapUsersUpdateSelectedListToState(event);
}
if (event is UsersStopSelecting) {
yield* _mapUsersStopSelectingToState();
}
}
@override
Future<void> close() async {
_usersSubscription.cancel();
super.close();
}
Stream<UsersState> _mapUsersFetchUserToState() async* {
yield state.copyWith(status: UsersStateStatus.loading);
try {
_usersSubscription?.cancel();
_usersSubscription = _userRepository.getAllUsers().listen((usersList) {
add(UsersUpdateUser(usersList: usersList));
});
} catch (e) {
yield state.copyWith(status: UsersStateStatus.error, error: e.message);
}
}
Stream<UsersState> _mapUsersUpdateUserToState(UsersUpdateUser event) async* {
// Removing the current user from the usersList
event.usersList.removeWhere(
(user) => user.id == _authBloc.state.user.uid,
);
yield state.copyWith(
usersList: event.usersList, status: UsersStateStatus.loaded);
}
Stream<UsersState> _mapUsersUpdateSearchListToState(
UsersUpdateSearchList event) async* {
List<User> results = [];
state.usersList.forEach((user) {
if (user.displayName.toLowerCase().contains(event.name.toLowerCase())) {
results.add(user);
}
});
if (state.status == UsersStateStatus.selecting) {
// User is selecting while searching
yield state.copyWith(
searchList: results, status: UsersStateStatus.selecting);
} else {
yield state.copyWith(
searchList: results,
status: UsersStateStatus.searching,
);
}
}
Stream<UsersState> _mapUsersStopSearchingToState() async* {
if (state.status == UsersStateStatus.selecting) {
// User was selecting while searching
yield state.copyWith(searchList: [], status: UsersStateStatus.selecting);
} else {
yield state.copyWith(searchList: [], status: UsersStateStatus.loaded);
}
}
Stream<UsersState> _mapUsersUpdateSelectedListToState(
UsersUpdateSelectedList event) async* {
final listCopy = [...state.selectedList];
if (state.selectedList.contains(event.user)) {
listCopy.remove(event.user);
if (listCopy.isEmpty) {
add(UsersStopSelecting());
} else {
yield state.copyWith(selectedList: listCopy);
}
} else {
listCopy.add(event.user);
yield state.copyWith(
selectedList: listCopy, status: UsersStateStatus.selecting);
}
}
Stream<UsersState> _mapUsersStopSelectingToState() async* {
yield state.copyWith(selectedList: [], status: UsersStateStatus.loaded);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/view_group/view_group_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
import 'package:wuphf_chat/screens/create_group/widgets/participants_widget.dart';
import 'package:wuphf_chat/screens/screens.dart';
import 'package:wuphf_chat/screens/view_profile/widgets/profile_picture.dart';
import 'package:wuphf_chat/helper/time_helper.dart';
class ViewGroupScreenArgs {
final String groupId;
ViewGroupScreenArgs({
@required this.groupId,
});
}
class ViewGroupScreen extends StatelessWidget {
static const String routeName = '/view-group-screen';
static Route route({@required ViewGroupScreenArgs args}) {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => BlocProvider<LiveGroupBloc>(
create: (context) => LiveGroupBloc(
groupId: args.groupId,
groupsRepository: context.read<GroupsRepository>(),
),
child: ViewGroupScreen(),
),
);
}
const ViewGroupScreen({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<LiveGroupBloc, LiveGroupState>(
builder: (context, state) {
if (state.status == LiveGroupStatus.loaded) {
final createdByUser = state.group.usersList
.firstWhere((element) => element.id == state.group.createdBy);
return CustomScrollView(
slivers: [
TwoTextAppBar(
title: state.group.groupName,
subtitle: 'Showing group details'),
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.fromLTRB(16.0, 32.0, 16.0, 0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePictureWidget(imageUrl: state.group.groupImage),
SizedBox(height: 32.0),
if (createdByUser.id ==
context.read<AuthBloc>().state.user.uid)
Column(
children: [
CustomElevatedButton(
onTap: () {
Navigator.pushNamed(
context,
EditGroupScreen.routeName,
arguments:
EditGroupArgs(group: state.group),
);
},
titleColor: Theme.of(context).primaryColor,
title: 'Edit Group Details',
buttonColor: Colors.white,
icon: FontAwesomeIcons.edit,
),
SizedBox(height: 16.0),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InputTitle(title: 'Created By'),
UserRow(
imageUrl: createdByUser.profileImageUrl,
title: createdByUser.displayName,
subtitle: createdByUser.bio,
isOnline: createdByUser.presence,
onChat: () {
Navigator.of(context).pushNamed(
ChattingScreen.routeName,
arguments: ChattingScreenArgs(
userId: createdByUser.id),
);
},
onView: () {
Navigator.of(context).pushNamed(
ViewProfileScreen.routeName,
arguments: ViewProfileScreenArgs(
user: createdByUser),
);
},
),
SizedBox(height: 12.0),
InputTitle(title: 'Created On'),
Padding(
padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 8.0),
child: Text(
state.group.createdAt.forCreatedAt(),
style: Theme.of(context).textTheme.subtitle1,
),
),
],
),
SizedBox(height: 12.0),
ParticipantsWidget(
participants: state.group.usersList,
showPresence: true,
),
],
),
),
)
],
);
}
return Center(
child: LoadingIndicator(),
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens | mirrored_repositories/flutter-wuphf-chat/lib/screens/chats/chats_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wuphf_chat/bloc/blocs.dart';
import 'package:wuphf_chat/global_widgets/global_widgets.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/screens/chats/bloc/chats_bloc.dart';
import 'package:wuphf_chat/screens/chatting/chatting_screen.dart';
import 'package:wuphf_chat/helper/time_helper.dart';
import 'package:wuphf_chat/screens/screens.dart';
class ChatsScreen extends StatefulWidget {
static const String routeName = "/chats-screen";
static Route route() {
return MaterialPageRoute(
settings: RouteSettings(name: routeName),
builder: (context) => ChatsScreen(),
);
}
const ChatsScreen({Key key}) : super(key: key);
@override
_ChatsScreenState createState() => _ChatsScreenState();
}
class _ChatsScreenState extends State<ChatsScreen> {
TextEditingController _textEditingController;
@override
void initState() {
super.initState();
_textEditingController = TextEditingController();
}
String createLastMessage({@required Message message, @required bool addYou}) {
String text = '';
if (addYou) {
text = 'You: ';
}
if (message.imageUrl != null && message.imageUrl.trim().isNotEmpty) {
text = text + '📷 ' + message.text;
return text;
}
return text + message.text;
}
void _search(String name) {
context.read<ChatsBloc>().add(SearchChats(name: name));
}
void _stopSearch() {
context.read<ChatsBloc>().add(StopSearch());
_textEditingController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<ChatsBloc, ChatsState>(
builder: (context, state) {
if (state.status == ChatsStatus.loaded ||
state.status == ChatsStatus.searching) {
List<ChatUser> chatList = state.status == ChatsStatus.searching
? state.searchList
: state.chatUsers;
return CustomScrollView(
physics: chatList.length == 0
? NeverScrollableScrollPhysics()
: BouncingScrollPhysics(),
slivers: [
SearchSliverAppBar(
title: 'Chats',
textEditingController: _textEditingController,
suffixActive: state.status == ChatsStatus.searching,
search: _search,
stopSearch: _stopSearch,
),
SliverPadding(
padding: EdgeInsets.fromLTRB(16.0, 8.0, 8.0, 0.0),
sliver: state.chatUsers.length == 0
? SliverToBoxAdapter(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
'assets/images/chat.png',
height: MediaQuery.of(context).size.width * 0.6,
width: MediaQuery.of(context).size.width * 0.6,
fit: BoxFit.fitHeight,
),
SizedBox(height: 16.0),
Text('No Chats To Show'),
],
),
)
: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final chatUser = chatList[index];
final addYou =
context.read<AuthBloc>().state.user.uid ==
chatUser.lastMessage.sentBy;
final text = createLastMessage(
message: chatUser.lastMessage,
addYou: addYou);
return UserRow(
isOnline: chatUser.user.presence,
title: chatUser.user.displayName,
subtitle: text,
imageUrl: chatUser.user.profileImageUrl,
date: chatUser.lastMessage.sentAt
.forLastMessage(),
onChat: () {
Navigator.of(context).pushNamed(
ChattingScreen.routeName,
arguments: ChattingScreenArgs(
userId: chatUser.user.id,
),
);
},
onView: () {
Navigator.of(context).pushNamed(
ViewProfileScreen.routeName,
arguments: ViewProfileScreenArgs(
user: chatUser.user),
);
},
);
},
childCount: chatList.length,
),
),
),
],
);
}
if (state.status == ChatsStatus.error) {
return Center(
child: Text('Something Went Wrong!'),
);
}
return Center(
child: LoadingIndicator(),
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chats | mirrored_repositories/flutter-wuphf-chat/lib/screens/chats/bloc/chats_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:wuphf_chat/models/models.dart';
import 'package:wuphf_chat/repositories/repositories.dart';
part 'chats_event.dart';
part 'chats_state.dart';
class ChatsBloc extends Bloc<ChatsEvent, ChatsState> {
final MessagesRepository _messagesRepository;
ChatsBloc({@required MessagesRepository messagesRepository})
: _messagesRepository = messagesRepository,
super(ChatsState.initial()) {
add(FetchChats());
}
StreamSubscription<List<ChatUser>> _chatsSubscription;
@override
Stream<ChatsState> mapEventToState(
ChatsEvent event,
) async* {
if (event is FetchChats) {
yield* _mapChatsFetchChatsToState();
}
if (event is UpdateChats) {
yield* _mapChatsUpdateChatsToState(event);
}
if (event is SearchChats) {
yield* _mapSearchChatsToState(event);
}
if (event is StopSearch) {
yield* _mapStopSearchToState();
}
}
Stream<ChatsState> _mapChatsFetchChatsToState() async* {
yield (state.copyWith(status: ChatsStatus.loading));
try {
_chatsSubscription?.cancel();
_chatsSubscription =
_messagesRepository.getUserChats().listen((chatUsersList) {
add(UpdateChats(chatUsers: chatUsersList));
});
} catch (e) {
yield (state.copyWith(status: ChatsStatus.error, error: e.message));
}
}
Stream<ChatsState> _mapChatsUpdateChatsToState(UpdateChats event) async* {
yield (state.copyWith(
chatUsers: event.chatUsers, status: ChatsStatus.loaded));
}
Stream<ChatsState> _mapSearchChatsToState(SearchChats event) async* {
List<ChatUser> results = [];
state.chatUsers.forEach((chatUser) {
if (chatUser.user.displayName
.toLowerCase()
.contains(event.name.toLowerCase())) {
results.add(chatUser);
}
});
yield state.copyWith(
searchList: results,
status: ChatsStatus.searching,
);
}
Stream<ChatsState> _mapStopSearchToState() async* {
yield (state.copyWith(
searchList: [],
status: ChatsStatus.loaded,
));
}
@override
Future<void> close() async {
_chatsSubscription.cancel();
super.close();
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chats | mirrored_repositories/flutter-wuphf-chat/lib/screens/chats/bloc/chats_state.dart | part of 'chats_bloc.dart';
enum ChatsStatus { initial, loading, loaded, searching, error }
class ChatsState extends Equatable {
final List<ChatUser> chatUsers;
final List<ChatUser> searchList;
final ChatsStatus status;
final String error;
const ChatsState({
@required this.chatUsers,
@required this.searchList,
@required this.status,
@required this.error,
});
factory ChatsState.initial() {
return ChatsState(
chatUsers: [],
searchList: [],
status: ChatsStatus.initial,
error: '',
);
}
@override
List<Object> get props => [chatUsers, searchList, status, error];
ChatsState copyWith({
List<ChatUser> chatUsers,
List<ChatUser> searchList,
ChatsStatus status,
String error,
}) {
return ChatsState(
chatUsers: chatUsers ?? this.chatUsers,
searchList: searchList ?? this.searchList,
status: status ?? this.status,
error: error ?? this.error,
);
}
}
| 0 |
mirrored_repositories/flutter-wuphf-chat/lib/screens/chats | mirrored_repositories/flutter-wuphf-chat/lib/screens/chats/bloc/chats_event.dart | part of 'chats_bloc.dart';
abstract class ChatsEvent extends Equatable {
const ChatsEvent();
@override
List<Object> get props => [];
}
class FetchChats extends ChatsEvent {}
class UpdateChats extends ChatsEvent {
final List<ChatUser> chatUsers;
UpdateChats({
@required this.chatUsers,
});
@override
List<Object> get props => [chatUsers];
}
class SearchChats extends ChatsEvent {
final String name;
SearchChats({@required this.name});
@override
List<Object> get props => [name];
}
class StopSearch extends ChatsEvent {}
| 0 |
mirrored_repositories/flutter-wuphf-chat | mirrored_repositories/flutter-wuphf-chat/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:wuphf_chat/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/note-it | mirrored_repositories/note-it/lib/main.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/app.dart';
import 'package:note_it/src/services/db_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized(); // Will throw an exception if not called before initiasing SQLite
await NotesDBService.getInstance();
runApp(App());
}
| 0 |
mirrored_repositories/note-it/lib | mirrored_repositories/note-it/lib/src/app.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/archived_notes.dart';
import 'package:note_it/src/screens/deleted_notes.dart';
import 'package:note_it/src/screens/notes.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/widgets/theme.dart';
import 'package:provider/provider.dart';
import 'models/note.dart';
import 'notifiers/drawer_notifier.dart';
class App extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => NoteNotifier()),
ChangeNotifierProvider(create: (_) => DrawerNotifier()),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: AppTheme().lightTheme,
home: NotesScreen(),
routes: {
NotesScreen.routeName: (BuildContext context) => NotesScreen(),
ArchivedNotesScreen.routeName: (BuildContext context) => ArchivedNotesScreen(),
DeletedNotesScreen.routeName: (BuildContext context) => DeletedNotesScreen()
// ViewNoteScreen.routeName: (BuildContext context) => ViewNoteScreen(note: Note(),)
},
),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/constants/app_strings.dart | class AppStrings{
static const String allNotes = 'All Notes';
static const String bookmarkedNotes = 'Bookmarked Notes';
static const String archivedNotes = 'Archived Notes';
static const String deletedNotes = 'Deleted Notes';
static const String bookmarks = 'Bookmarks';
static const String all = 'All';
static const String tags = 'Tags';
static const String noNotes = 'Oops! No notes here.';
static const String editing = 'Editing';
static const String viewing = 'Viewing';
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/notifiers/note_notifier.dart | import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/services/db_service.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqflite.dart';
class NoteNotifier with ChangeNotifier {
static NoteNotifier of(BuildContext context) =>
Provider.of<NoteNotifier>(context, listen: false);
// NotesDBService _localDBService;
// Database _db;
List<Note> _notes = [];
List<Note> get notes => _notes
.where((note) => note.isArchived == false && note.isSoftDeleted == false)
.toList();
List<Note> get bookmarkedNotes =>
notes.where((note) => note.isBookmarked == true).toList();
List<Note> get archivedNotes =>
_notes.where((note) => note.isArchived == true).toList();
List<Note> get deletedNotes =>
_notes.where((note) => note.isSoftDeleted == true).toList();
// Future<void> init() async =>
// _localDBService = await NotesDBService.getInstance();
Future<void> addNote(Note note) async {
final dbService = await NotesDBService.getInstance();
final noteId = await dbService.addNote(note);
note.id = noteId;
_notes.add(note);
notifyListeners();
}
Future<List<Note>> getNotes() async {
final dbService = await NotesDBService.getInstance();
final notes = await dbService.getNotes();
_notes
.clear(); // To prevent duplicate notes i.e addding the same notes to the previous notes
_notes.addAll(notes);
notifyListeners();
return notes;
}
Future<void> editNote(Note updatedNote) async {
final dbService = await NotesDBService.getInstance();
await dbService.editNote(updatedNote);
final oldNoteIndex = _notes.indexWhere((note) => note.id == updatedNote.id);
_notes.replaceRange(oldNoteIndex, oldNoteIndex + 1, [updatedNote]);
notifyListeners();
}
Future<void> hardDeleteNote(Note noteToDelete) async {
final dbService = await NotesDBService.getInstance();
await dbService.hardDeleteNote(noteToDelete);
_notes.removeWhere((note) => note.id == noteToDelete.id);
notifyListeners();
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/notifiers/drawer_notifier.dart | import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
class DrawerNotifier with ChangeNotifier {
static DrawerNotifier of(BuildContext context) =>
Provider.of<DrawerNotifier>(context, listen: false);
int _currentlySelectedIndex = 0;
int get currentlySelectedIndex => _currentlySelectedIndex;
void updateSelectedIndex(int newIndex) {
_currentlySelectedIndex = newIndex;
notifyListeners();
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/widgets/bottom_app_bar.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class AppBottomNavigationBarItem {
AppBottomNavigationBarItem({this.iconData, this.text});
IconData iconData;
String text;
}
class AppBottomNavigationBar extends StatefulWidget {
final ValueChanged<int> onTabSelected;
final List <AppBottomNavigationBarItem> items;
final Color color;
final Color selectedColor;
final double height;
final double iconSize;
const AppBottomNavigationBar(
{this.onTabSelected, this.items, this.color = Colors.grey, this.selectedColor = Colors.black, this.height = 60, this.iconSize = 24});
@override
_AppBottomNavigationBarState createState() => _AppBottomNavigationBarState();
}
class _AppBottomNavigationBarState extends State<AppBottomNavigationBar> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return BottomAppBar(
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _items(),
),
);
}
List<Widget> _items() {
return List.generate(widget.items.length, (int index) {
return _buildTabItem(
navigationBarItem: widget.items[index],
index: index,
onPressed: _updateSelectedIndex
);
});
}
Widget _buildTabItem(
{AppBottomNavigationBarItem navigationBarItem, int index, ValueChanged<int> onPressed}) {
Color color = _selectedIndex == index ? widget.selectedColor : widget.color;
return Expanded(
child: SizedBox(
height: widget.height,
child: Material(
type: MaterialType.transparency,
child: InkWell(
onTap: () => onPressed(index),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(navigationBarItem.iconData, color: color, size: widget.iconSize,),
Text(navigationBarItem.text, style: TextStyle(
color: color
),)
],
),
),
),
)
);
}
_updateSelectedIndex(int index) {
widget.onTabSelected(index);
setState(() {
_selectedIndex = index;
});
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/widgets/theme.dart | import 'package:flutter/material.dart';
class AppTheme {
ThemeData get lightTheme {
return ThemeData.light().copyWith(
primaryColor: Colors.white,
accentColor: Colors.black,
appBarTheme: AppBarTheme(
color: Colors.white,
elevation: 0.0,
textTheme: TextTheme(
title: TextStyle(
color: Colors.black,
)
),
iconTheme: IconThemeData(
color: Colors.black,
)
)
);
}
ThemeData get darkTheme {
return ThemeData.dark().copyWith(
primaryColor: Colors.black45,
accentColor: Colors.white,
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/widgets/drawer.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/notifiers/drawer_notifier.dart';
import 'package:note_it/src/screens/archived_notes.dart';
import 'package:note_it/src/screens/deleted_notes.dart';
import 'package:note_it/src/screens/notes.dart';
import 'package:provider/provider.dart';
class AppDrawerTileItem {
AppDrawerTileItem({this.title, this.iconData, this.destinationRoute});
String title;
IconData iconData;
String destinationRoute;
}
final tileItems = [
AppDrawerTileItem(
title: 'Notes',
iconData: Icons.lightbulb_outline,
destinationRoute: NotesScreen.routeName),
AppDrawerTileItem(
title: 'Archived Notes',
iconData: Icons.archive,
destinationRoute: ArchivedNotesScreen.routeName),
AppDrawerTileItem(
title: 'Deleted Notes',
iconData: Icons.delete,
destinationRoute: DeletedNotesScreen.routeName)
];
class AppDrawer extends StatefulWidget {
@override
_AppDrawerState createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
DrawerNotifier _drawerNotifier;
Color _selectedColor = Colors.black;
Color _unselectedColor = Colors.grey;
@override
Widget build(BuildContext context) {
_drawerNotifier = DrawerNotifier.of(context);
return SafeArea(
child: Drawer(
child: Consumer<DrawerNotifier>(
builder: (context, drawer, child) {
return ListView(
children: <Widget>[
..._buildDrawerListTiles(
currentlySelectedIndex: drawer.currentlySelectedIndex)
],
);
},
),
),
);
}
_buildDrawerListTiles({int currentlySelectedIndex}) {
return List.generate(tileItems.length, (int index) {
final tileItem = tileItems[index];
Color color =
currentlySelectedIndex == index ? _selectedColor : _unselectedColor;
return _buildDrawerListTile(
index: index,
title: tileItem.title,
iconData: tileItem.iconData,
destinationRoute: tileItem.destinationRoute,
color: color);
});
}
Widget _buildDrawerListTile(
{int index,
String title,
IconData iconData,
String destinationRoute,
Color color}) {
return ListTile(
leading: Icon(iconData, color: color),
title: Text(
title,
style: Theme.of(context).textTheme.body1.copyWith(color: color),
),
onTap: () => _handleTilePress(index, destinationRoute),
);
}
_handleTilePress(int index, String destinationRoute) {
int _currentlySelectedIndex = _drawerNotifier.currentlySelectedIndex;
if (index == _currentlySelectedIndex) {
Navigator.pop(context); // Close drawer
return;
}
Navigator.pop(context); // Close drawer
Navigator.pushReplacementNamed(context, destinationRoute);
_drawerNotifier.updateSelectedIndex(index);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/widgets/note_list.dart |
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/utils/utils.dart';
class NoteListTile extends StatelessWidget {
final Note note;
final VoidCallback onNoteTapped;
NoteListTile({this.note, this.onNoteTapped});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
onNoteTapped();
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(bottom: 5),
child: Text(
note.title,
style: TextStyle(fontSize: 18),
),
),
Container(
margin: EdgeInsets.only(bottom: 5),
child: Text(
note.content,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14),
),
),
Container(
margin: EdgeInsets.only(bottom: 5),
child: Text(
'${beautifyDate(note.dateLastModified)} at ${beautifyTime(note.dateLastModified)}',
style: TextStyle(fontSize: 11),
),
),
if (note.tagName.isNotEmpty)
Row(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 7, vertical: 1),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.all(Radius.circular(4))),
child: Text(
note.tagName,
style: TextStyle(color: Colors.white),
),
)
],
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/widgets/no_notes_info.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
class NoNoteInfo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
AppStrings.noNotes,
style: Theme.of(context).textTheme.display1.copyWith(fontSize: 14),
),
],
),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/models/popup_menu_option.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/models/note.dart';
enum PopupMenuValue {
soft_delete,
hard_delete,
restore,
archive,
unarchive,
bookmark,
unbookmark
}
class PopupMenuOption {
PopupMenuValue value;
String label;
IconData iconData;
PopupMenuOption({this.value, this.label, this.iconData});
}
List<PopupMenuOption> deletedNoteOptions = [
PopupMenuOption(
value: PopupMenuValue.hard_delete,
label: 'Delete Forever',
iconData: Icons.ac_unit),
PopupMenuOption(
value: PopupMenuValue.restore, label: 'Restore', iconData: Icons.ac_unit),
];
final popUpMenuOptions = [
PopupMenuOption(
value: PopupMenuValue.archive, label: 'Archive', iconData: Icons.ac_unit),
PopupMenuOption(
value: PopupMenuValue.unarchive,
label: 'Unarchive',
iconData: Icons.ac_unit),
PopupMenuOption(
value: PopupMenuValue.soft_delete,
label: 'Delete',
iconData: Icons.ac_unit),
];
List<PopupMenuOption> getMenuOptionsForNote({Note note}) {
List<PopupMenuOption> menuOptions = [
// Unarchived note options
if (!note.isArchived && !note.isSoftDeleted) ...[
PopupMenuOption(
value: PopupMenuValue.archive,
label: 'Archive',
iconData: Icons.ac_unit),
PopupMenuOption(
value: PopupMenuValue.soft_delete,
label: 'Delete',
iconData: Icons.ac_unit),
if (note.isBookmarked)
PopupMenuOption(
value: PopupMenuValue.unbookmark,
label: 'Unbookmark',
iconData: Icons.ac_unit),
if (!note.isBookmarked)
PopupMenuOption(
value: PopupMenuValue.bookmark,
label: 'Bookmark',
iconData: Icons.ac_unit),
],
// Archived note options
if (note.isArchived && !note.isSoftDeleted) ...[
PopupMenuOption(
value: PopupMenuValue.unarchive,
label: 'Unarchive',
iconData: Icons.ac_unit),
PopupMenuOption(
value: PopupMenuValue.soft_delete,
label: 'Delete',
iconData: Icons.ac_unit),
],
if (note.isSoftDeleted)
...deletedNoteOptions
];
// // Unarchived note
// if (!note.isArchived && !note.isSoftDeleted) {
// menuOptions.addAll(
// [
// PopupMenuOption(
// value: PopupMenuValue.archive,
// label: 'Archive',
// iconData: Icons.ac_unit),
// PopupMenuOption(
// value: PopupMenuValue.soft_delete,
// label: 'Delete',
// iconData: Icons.ac_unit),
// if (note.isBookmarked)
// PopupMenuOption(
// value: PopupMenuValue.unbookmark,
// label: 'Unbookmark',
// iconData: Icons.ac_unit),
// if (!note.isBookmarked)
// PopupMenuOption(
// value: PopupMenuValue.bookmark,
// label: 'Bookmark',
// iconData: Icons.ac_unit),
// ],
// );
// }
// //Archived Note
// if (note.isArchived && !note.isSoftDeleted) {
// menuOptions.addAll([
// PopupMenuOption(
// value: PopupMenuValue.unarchive,
// label: 'Unarchive',
// iconData: Icons.ac_unit),
// PopupMenuOption(
// value: PopupMenuValue.soft_delete,
// label: 'Delete',
// iconData: Icons.ac_unit),
// ]);
// }
// // Soft deleted note
// if (note.isSoftDeleted) menuOptions.addAll(deletedNoteOptions);
return menuOptions;
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/models/note.dart | import 'package:date_format/date_format.dart';
class Note {
int id = 0;
String title = '';
String content = '';
String dateCreated = DateTime.now().toIso8601String();
String dateLastModified = DateTime.now().toIso8601String();
bool isArchived = false;
bool isSoftDeleted = false;
bool isBookmarked = false;
String tagName = '';
bool _mapIntegerToBool(int value) => value == 1 ? true : false;
// bool get isNew => this.title.isEmpty && this.content.isEmpty;
// We're initialising the date outside the constructor brackets because
// The default value of an optional parameter must be constant.
// See error: dartnon_constant_default_value
Note();
Note.from(
{this.id,
this.title,
this.content,
this.dateCreated,
this.dateLastModified,
this.isArchived,
this.isSoftDeleted,
this.isBookmarked});
Note.dummy(
{this.id = 0,
this.title = 'A note on colonisation',
this.content =
'Colonial Masters decided to colonise. What the hell am I saying?',
this.tagName = '',
this.isArchived = false,
this.isSoftDeleted = false, this.isBookmarked})
: this.dateCreated = DateTime.now().toIso8601String(),
this.dateLastModified = DateTime.now().toIso8601String();
Note.copyOf(Note note) {
id = note.id;
title = note.title;
content = note.content;
dateCreated = note.dateCreated;
dateLastModified = note.dateLastModified;
tagName = note.tagName;
isArchived = note.isArchived;
isSoftDeleted = note.isSoftDeleted;
isBookmarked = note.isBookmarked;
}
Note copyWith({bool isArchived, bool isSoftDeleted, bool isBookmarked}) {
return Note.from(
id: this.id,
title: this.title,
content: this.content,
dateCreated: this.dateCreated,
dateLastModified: this.dateLastModified,
isSoftDeleted: isSoftDeleted ?? this.isSoftDeleted,
isArchived: isArchived ?? this.isArchived,
isBookmarked: isBookmarked ?? this.isBookmarked);
}
Note.fromMap(Map json) {
id = json['id'];
title = json['title'];
content = json['content'];
dateCreated = json['date_created'];
dateLastModified = json['date_last_modified'];
isArchived = _mapIntegerToBool(json['is_archived']);
isSoftDeleted = _mapIntegerToBool(json['is_soft_deleted']);
isBookmarked = _mapIntegerToBool(json['is_bookmarked']);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = Map();
// id will be auto generated in the db
map['title'] = title;
map['content'] = content;
map['date_created'] = dateCreated;
map['date_last_modified'] = dateLastModified;
map['is_archived'] = isArchived ? 1 : 0;
map['is_soft_deleted'] = isSoftDeleted ? 1 : 0;
map['is_bookmarked'] = isBookmarked ? 1 : 0;
return map;
}
@override
String toString() {
return ''
// 'id - $id, '
'title - $title, '
'content - $content, '
'date_created - $dateCreated, '
'date_last_modified - $dateLastModified, '
'is_archived - $isArchived, '
'is_soft_deleted - $isSoftDeleted, '
'is_bookmarked - $isBookmarked, ';
}
}
List<Note> getDummyNotes() {
return List.generate(0, (_) => Note.dummy());
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/utils/utils.dart | import 'package:date_format/date_format.dart';
String beautifyDate(String rawDate) {
return formatDate(DateTime.parse(rawDate), [d, ' ', M, ' ', yyyy]);
}
String beautifyTime(String rawDate) {
return formatDate(DateTime.parse(rawDate), [HH, ':', nn,]);
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/services/db_service.dart | import 'dart:async';
import 'package:note_it/src/models/note.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path;
class NotesDBService {
static final tableName = 'notes';
static final dbName = 'notes.db';
static final _sqlString =
'CREATE TABLE notes(id INTEGER PRIMARY KEY, title TEXT, content TEXT, date_created TEXT, date_last_modified TEXT, is_archived INTEGER, is_soft_deleted INTEGER, is_bookmarked INTEGER)';
static Database _db;
NotesDBService._();
static Future<NotesDBService> getInstance() async {
_db ??= await _openDb();
return NotesDBService._();
} // instance variables can't be accessed from static variables
static Future<Database> _openDb() async {
final databasesPath = await getDatabasesPath();
final dbPath = path.join(databasesPath, dbName);
final db = openDatabase(dbPath, version: 1, onCreate: _createDB);
return db;
}
/// Only called if the db has not been created in the device
static Future<void> _createDB(Database db, int version) =>
db.execute(_sqlString);
Future<int> addNote(Note note) async {
final map = note.toMap();
final noteId = await _db.insert(tableName, map,
conflictAlgorithm: ConflictAlgorithm.replace);
return noteId;
}
Future<int> editNote(Note editedNote) async {
final map = editedNote.toMap();
final affectedRows = await _db
.update(tableName, map, where: 'id = ?', whereArgs: [editedNote.id]);
return affectedRows;
}
Future<List<Note>> getNotes() async {
final maps = await _db.query(tableName);
return List.generate(maps.length, (index) => Note.fromMap(maps[index]));
}
Future<int> hardDeleteNote(Note note) async {
final affectedRows =
await _db.delete(tableName, where: "id = ?", whereArgs: [note.id]);
return affectedRows;
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/deleted_notes.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/widgets/drawer.dart';
import 'package:note_it/src/widgets/no_notes_info.dart';
import 'package:note_it/src/widgets/note_list.dart';
import 'package:provider/provider.dart';
class DeletedNotesScreen extends StatefulWidget {
static final String routeName = 'deleted_notes';
@override
_DeletedNotesScreenState createState() => _DeletedNotesScreenState();
}
class _DeletedNotesScreenState extends State<DeletedNotesScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppStrings.deletedNotes),
centerTitle: true,
actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
drawer: AppDrawer(),
body: Consumer<NoteNotifier>(
builder: (context, noteNotifier, _) {
print('rebuilding deleted notes');
return noteNotifier.deletedNotes.isEmpty
? NoNoteInfo()
: Container(
// margin: EdgeInsets.symmetric(horizontal: 15),
child: ListView.separated(
itemCount: noteNotifier.deletedNotes.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
Note note = noteNotifier.deletedNotes[index];
Theme.of(context).textTheme.copyWith();
return NoteListTile(
note: note,
onNoteTapped: () {
_goToViewNoteScreen(note: note);
},
);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
backgroundColor: Theme.of(context).accentColor,
onPressed: () {
_goToViewNoteScreen(note: Note(), isNewNote: true);
},
tooltip: 'Add Note',
child: Icon(Icons.add),
),
);
}
void _goToViewNoteScreen({Note note, bool isNewNote = false}) {
// print('entering note: $note');
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return ViewNoteScreen(
note: note,
isNewNote: isNewNote,
);
}),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/archived_notes.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/widgets/drawer.dart';
import 'package:note_it/src/widgets/no_notes_info.dart';
import 'package:note_it/src/widgets/note_list.dart';
import 'package:provider/provider.dart';
class ArchivedNotesScreen extends StatefulWidget {
static final String routeName = 'archived_notes';
@override
_ArchivedNotesScreenState createState() => _ArchivedNotesScreenState();
}
class _ArchivedNotesScreenState extends State<ArchivedNotesScreen> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(AppStrings.archivedNotes),
),
drawer: AppDrawer(),
body: Consumer<NoteNotifier>(
builder: (context, noteNotifier, _) {
print('rebuilding archived notes');
return noteNotifier.archivedNotes.isEmpty
? NoNoteInfo()
: Container(
// margin: EdgeInsets.symmetric(horizontal: 15),
child: ListView.separated(
itemCount: noteNotifier.archivedNotes.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
Note note = noteNotifier.archivedNotes[index];
return NoteListTile(
note: note,
onNoteTapped: () {
_goToViewNoteScreen(note: note);
},
);
},
),
);
},
),
),
);
}
void _goToViewNoteScreen({Note note, bool isNewNote = false}) {
// print('entering note: $note');
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return ViewNoteScreen(
note: note,
isNewNote: isNewNote,
);
}),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/notes.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/bookmarked_notes.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/utils/utils.dart';
import 'package:note_it/src/widgets/bottom_app_bar.dart';
import 'package:note_it/src/widgets/drawer.dart';
import 'package:provider/provider.dart';
import 'all_notes.dart';
class NotesScreen extends StatefulWidget {
static final String routeName = 'notes';
@override
_NotesScreenState createState() => _NotesScreenState();
}
class _NotesScreenState extends State<NotesScreen> {
int _currentTabIndex = 0;
NoteNotifier _noteNotifier;
final tabs = [
AllNotesScreen(),
BookmarkedNotesScreen(),
];
//TODO: Load data before showing tabs?
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
final notes = await _noteNotifier.getNotes();
// for (var note in notes) {
// print(note);
// }
// setState(() {});
});
}
@override
Widget build(BuildContext context) {
// print('rebuilding home.dart');
_noteNotifier = NoteNotifier.of(context);
return SafeArea(
child: Scaffold(
// drawer: AppDrawer(),
body: tabs[_currentTabIndex],
bottomNavigationBar: AppBottomNavigationBar(
onTabSelected: _changeTab,
items: [
AppBottomNavigationBarItem(
iconData: Icons.book, text: AppStrings.all),
AppBottomNavigationBarItem(
iconData: Icons.star, text: AppStrings.bookmarks),
// AppBottomNavigationBarItem(iconData: Icons.label, text: 'Tags')
],
),
),
);
}
void _changeTab(int nextTabIndex) {
setState(() {
_currentTabIndex = nextTabIndex;
});
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/view_note.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/models/popup_menu_option.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/utils/utils.dart';
enum PageMode { edit, view }
class ViewNoteScreen extends StatefulWidget {
static final String routeName = 'view_note';
final Note note;
final bool isNewNote;
ViewNoteScreen({this.note, this.isNewNote = false});
@override
_ViewNoteScreenState createState() => _ViewNoteScreenState();
}
class _ViewNoteScreenState extends State<ViewNoteScreen> {
Note _note;
bool _isNewNote;
PageMode _pageMode;
TextEditingController _titleController;
TextEditingController _contentController;
FocusNode _titleFocusNode;
FocusNode _contentFocusNode;
NoteNotifier _noteNotifier;
bool get _isInEditMode => _pageMode == PageMode.edit;
@override
void initState() {
super.initState();
_note = Note.copyOf(widget.note);
_isNewNote = widget.isNewNote;
_titleController = TextEditingController(text: _note.title);
_contentController = TextEditingController(text: _note.content);
_titleFocusNode = FocusNode();
_contentFocusNode = FocusNode();
_pageMode = _isNewNote ? PageMode.edit : PageMode.view;
// print(widget.note.title);
}
@override
void dispose() {
_titleController.dispose();
_contentController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_noteNotifier = NoteNotifier.of(context);
// print(note.isNew);
// print(_pageMode);
return Scaffold(
appBar: AppBar(
title: Text(_isInEditMode ? AppStrings.editing : AppStrings.viewing),
actions: <Widget>[
PopupMenuButton(
onSelected: _onMenuOptionSelected,
itemBuilder: (context) {
var menuOptions = getMenuOptionsForNote(note: _note);
return menuOptions.map(
(menuOption) {
return PopupMenuItem(
value: menuOption.value,
child: Text(menuOption.label),
);
},
).toList();
},
),
],
),
body: WillPopScope(
onWillPop: _onBackButtonPressed,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
_buildTitleField(),
Divider(),
_buildDateAndTimeText(),
_buildContentField(),
],
),
),
),
),
);
}
Widget _buildTitleField() {
return TextField(
controller: _titleController,
autofocus: _isNewNote,
focusNode: _titleFocusNode,
onTap: () {
_startEditingIfViewing();
},
style: TextStyle(fontSize: 30),
decoration: InputDecoration(
hintText: 'Title',
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
contentPadding: EdgeInsets.only(top: 8),
isDense: true, // Makes text field compact
),
);
}
Widget _buildDateAndTimeText() {
return Container(
margin: EdgeInsets.only(bottom: 10),
child: Row(
// TODO: Maybe we should use a TextSpan instead?
children: <Widget>[
Text('${beautifyDate(_note.dateCreated)}\t'),
// SizedBox(
// width: 30,
// ),
Text('\t${beautifyTime(_note.dateCreated)}')
],
),
);
}
Widget _buildContentField() {
return TextField(
onTap: () {
_startEditingIfViewing();
},
controller: _contentController,
focusNode: _contentFocusNode,
maxLines: null, // Makes text to wrap to next line
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
hintText: 'Body',
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
contentPadding: EdgeInsets.only(top: 8),
fillColor: Colors.amber,
isDense: true, // Makes text field compact
),
);
}
void _onMenuOptionSelected(PopupMenuValue newValue) async {
print('selected option: $newValue');
switch (newValue) {
case PopupMenuValue.soft_delete:
await _noteNotifier.editNote(_note.copyWith(isSoftDeleted: true));
Navigator.of(context).pop();
break;
case PopupMenuValue.restore:
await _noteNotifier.editNote(_note.copyWith(isSoftDeleted: false));
Navigator.of(context).pop();
break;
case PopupMenuValue.hard_delete:
await _noteNotifier.hardDeleteNote(_note);
Navigator.of(context).pop();
break;
case PopupMenuValue.archive:
await _noteNotifier.editNote(_note.copyWith(isArchived: true));
Navigator.of(context).pop();
break;
case PopupMenuValue.unarchive:
await _noteNotifier.editNote(_note.copyWith(isArchived: false));
Navigator.of(context).pop();
break;
case PopupMenuValue.bookmark:
await _noteNotifier.editNote(_note.copyWith(isBookmarked: true));
Navigator.of(context).pop();
break;
case PopupMenuValue.unbookmark:
await _noteNotifier.editNote(_note.copyWith(isBookmarked: false));
Navigator.of(context).pop();
break;
default:
}
}
void _startEditingIfViewing() {
if (!_isInEditMode) {
setState(() {
_pageMode = PageMode.edit;
});
}
}
/// Determines what to do when the back button is presses
/// It pops the screen if it returns false, and doesn't pop
/// the screen if it returns true
Future<bool> _onBackButtonPressed() async {
_bundleNote(_isNewNote);
print('Is new note: $_isNewNote');
// In view mode
if (!_isInEditMode) {
return true;
}
//In edit mode
if (_isInEditMode) {
FocusScope.of(context)
.requestFocus(FocusNode()); // Unfocus from textfields
setState(() {
_pageMode = PageMode.view;
});
// Add note
if (_isNewNote) {
setState(() {
_isNewNote = false;
});
print('Added note...');
await _noteNotifier.addNote(_note);
return false;
}
// Update note
if (!_isNewNote) {
// print('Updated note...');
//TODO: Update note here if the note has changed
await _noteNotifier.editNote(_note);
print('saving note: $_note');
}
}
return false; // Don't pop screen if in edit mode
}
void _bundleNote(bool isNewNote) {
if (!isNewNote) {
_note.dateLastModified = DateTime.now().toIso8601String();
}
_note.title = _titleController.text.isNotEmpty
? _titleController.text
: 'Untitled Note';
_note.content = _contentController.text;
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/bookmarked_notes.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/widgets/drawer.dart';
import 'package:note_it/src/widgets/no_notes_info.dart';
import 'package:note_it/src/widgets/note_list.dart';
import 'package:provider/provider.dart';
class BookmarkedNotesScreen extends StatefulWidget {
@override
_BookmarkedNotesScreenState createState() => _BookmarkedNotesScreenState();
}
class _BookmarkedNotesScreenState extends State<BookmarkedNotesScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppStrings.bookmarkedNotes),
centerTitle: true,
actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
drawer: AppDrawer(),
body: Consumer<NoteNotifier>(
builder: (context, noteNotifier, _) {
print('rebuilding bookmarked notes');
return noteNotifier.bookmarkedNotes.isEmpty
? NoNoteInfo()
: Container(
// margin: EdgeInsets.symmetric(horizontal: 15),
child: ListView.separated(
itemCount: noteNotifier.bookmarkedNotes.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
Note note = noteNotifier.bookmarkedNotes[index];
return NoteListTile(
note: note,
onNoteTapped: () {
_goToViewNoteScreen(note: note);
},
);
},
),
);
},
),
);
}
void _goToViewNoteScreen({Note note, bool isNewNote = false}) {
// print('entering note: $note');
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return ViewNoteScreen(
note: note,
isNewNote: isNewNote,
);
}),
);
}
}
| 0 |
mirrored_repositories/note-it/lib/src | mirrored_repositories/note-it/lib/src/screens/all_notes.dart | import 'package:flutter/material.dart';
import 'package:note_it/src/constants/app_strings.dart';
import 'package:note_it/src/models/note.dart';
import 'package:note_it/src/notifiers/note_notifier.dart';
import 'package:note_it/src/screens/view_note.dart';
import 'package:note_it/src/widgets/drawer.dart';
import 'package:note_it/src/widgets/no_notes_info.dart';
import 'package:note_it/src/widgets/note_list.dart';
import 'package:provider/provider.dart';
class AllNotesScreen extends StatefulWidget {
@override
_AllNotesScreenState createState() => _AllNotesScreenState();
}
class _AllNotesScreenState extends State<AllNotesScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppStrings.allNotes),
centerTitle: true,
actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
drawer: AppDrawer(),
body: Consumer<NoteNotifier>(
builder: (context, noteNotifier, _) {
print('rebuilding all notes');
return noteNotifier.notes.isEmpty
? NoNoteInfo()
: Container(
// margin: EdgeInsets.symmetric(horizontal: 15),
child: ListView.separated(
itemCount: noteNotifier.notes.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
Note note = noteNotifier.notes[index];
Theme.of(context).textTheme.copyWith();
return NoteListTile(
note: note,
onNoteTapped: () {
_goToViewNoteScreen(note: note);
},
);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
backgroundColor: Theme.of(context).accentColor,
onPressed: () {
_goToViewNoteScreen(note: Note(), isNewNote: true);
},
tooltip: 'Add Note',
child: Icon(Icons.add),
),
);
}
void _goToViewNoteScreen({Note note, bool isNewNote = false}) {
// print('entering note: $note');
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return ViewNoteScreen(
note: note,
isNewNote: isNewNote,
);
}),
);
}
}
| 0 |
mirrored_repositories/note-it | mirrored_repositories/note-it/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:note_it/main.dart';
import 'package:note_it/src/app.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(App());
// 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 | mirrored_repositories/percentage-calculation-application/home_page.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yuzde_hesapla/buttons.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//var _restoranAdresiController = TextEditingController();
var _meblagController = TextEditingController();
var _yuzdeController = TextEditingController();
//TextEditingController _meblagController;
//TextEditingController _yuzdeController;
String _meblag;
String _yuzde;
//TextEditingController _sonuc;
double _sonuc = 0.0;
int _hesapYontemi;
var toggleValues = [true, false, false];
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
/*REKLAM SON HALİ
AdmobIslemleri.myBannerAd = AdmobIslemleri.buildBannerAd();
AdmobIslemleri.myBannerAd
..load()
..show(anchorOffset: 180);
print(
" #################### banner kullanıcı sayfasında gosterilecek ######################");
*/
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildTutarGirdisi(),
_buildYuzdeGirdisi(),
_buildHesapYontemiSec(),
_hesaplaButonu(),
_buildSonucGoster(),
],
),
),
);
}
/*
TextFormField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
labelText:"whatever you want",
hintText: "whatever you want",
icon: Icon(Icons.phone_iphone)
)
)*/
Widget _buildTutarGirdisi() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _meblagController,
keyboardType:
TextInputType.number, //bu satır input kalvyesini sayı yapıyor
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
labelText: "Meblağ",
hintText: "Başlangıç Tutarını Girin",
border: OutlineInputBorder(),
icon: Transform.scale(
scale: 1.5,
child: Icon(Icons.input)), //input yanında çıkan iconun rengi
fillColor: Colors.deepPurple), //input yanında çıkan ikon
style: TextStyle(
fontSize: 20.0, color: Colors.black, fontWeight: FontWeight.bold),
),
);
}
Widget _buildYuzdeGirdisi() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _yuzdeController,
keyboardType:
TextInputType.number, //bu satır input kalvyesini sayı yapıyor
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
labelText: "Yüzde",
hintText: "Yüzde Değişimi Girin",
border: OutlineInputBorder(),
icon: Transform.scale(
scale: 1.5,
child:
Icon(Icons.calculate)), //input yanında çıkan iconun rengi
fillColor: Colors.deepPurple), //input yanında çıkan ikon
style: TextStyle(
fontSize: 20.0, color: Colors.black, fontWeight: FontWeight.bold),
),
);
}
Widget _buildSonucGoster() {
var sonucGoster = _sonuc.toString();
if (sonucGoster == null) {
sonucGoster = "";
}
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
sonucGoster,
style: TextStyle(
fontSize: 40.0, color: Colors.black, fontWeight: FontWeight.bold),
),
/*TextFormField(
//controller: _meblag,
//keyboardType: TextInputType.number, //bu satır input kalvyesini sayı yapıyor
//inputFormatters: <TextInputFormatter>[WhitelistingTextInputFormatter.digitsOnly],
readOnly: true,
decoration: InputDecoration(
labelText: "Sonuç",
hintText: "Hesaplama Sonucu",
// border: OutlineInputBorder(),
icon: Transform.scale(
scale: 1.5,
child: Icon(Icons.score)), //input yanında çıkan iconun rengi
fillColor: Colors.deepPurple), //input yanında çıkan icon
style: TextStyle(
fontSize: 20.0, color: Colors.black, fontWeight: FontWeight.bold),
),*/
);
}
Widget _buildHesapYontemiSec() {
var sembolAraligi = 1.0;
var islemAraligi = 30.0;
var yaziSize = 20.0;
return Center(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Container(
child: Text(
"",
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
),
),
),
),
SizedBox(width: sembolAraligi),
Transform.scale(
scale: 1.5,
child: Radio(
groupValue: _hesapYontemi,
value: 1,
onChanged: (t) {
setState(() {
_hesapYontemi = t;
});
},
),
),
//Icon(Icons.add),
SizedBox(width: sembolAraligi),
Text(
"+ %",
style: TextStyle(
fontSize: yaziSize,
color: Colors.black,
fontWeight: FontWeight.bold),
),
SizedBox(width: islemAraligi),
Transform.scale(
scale: 1.5,
child: Radio(
groupValue: _hesapYontemi,
value: 2,
onChanged: (t) {
setState(() {
_hesapYontemi = t;
});
},
),
),
//Icon(Icons.minimize_outlined),
SizedBox(width: sembolAraligi),
Text(
"- %",
style: TextStyle(
fontSize: yaziSize,
color: Colors.black,
fontWeight: FontWeight.bold),
),
SizedBox(width: islemAraligi),
Transform.scale(
scale: 1.5,
child: Radio(
groupValue: _hesapYontemi,
value: 3,
onChanged: (t) {
setState(() {
_hesapYontemi = t;
print("_hesapYontemi: " + _hesapYontemi.toString());
});
},
),
),
SizedBox(width: sembolAraligi),
Text(
"= %",
style: TextStyle(
fontSize: yaziSize,
color: Colors.black,
fontWeight: FontWeight.bold),
),
SizedBox(width: sembolAraligi),
Expanded(
child: Container(
child: Text(
"",
style: TextStyle(
color: Colors.white,
fontSize: yaziSize,
),
),
),
),
],
),
),
),
);
}
Widget _hesaplaButonu() {
return Container(
margin: EdgeInsets.symmetric(
horizontal: 4,
),
child: RawMaterialButton(
elevation: 0,
fillColor: Colors.deepPurple,
/*child:Icon(
Icons.check,
size: 35,
color: Colors.white,
),*/
child: Text(
"Hesapla",
style: Theme.of(context).textTheme.subtitle.copyWith(
color: Colors.white,
fontSize: 20.0,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
onPressed: () async {
_sonuc = await _hesapla();
setState(() {
_buildSonucGoster();
});
},
),
);
}
double _hesapla() {
var meblag;
var yuzde;
var sonuc;
print("_meblag: " + _meblagController.toString());
if (_meblagController.text.trim().length > 0) {
if (_yuzdeController.text.trim().length > 0) {
_meblag = _meblagController.text;
meblag = int.parse(_meblag);
_yuzde = _yuzdeController.text;
yuzde = int.parse(_yuzde);
if (meblag > 0) {
if (yuzde > 0) {
print("meblag 0 dan büyük: " + meblag.toString());
print("yuzde 0 dan büyük: " + yuzde.toString());
if (_hesapYontemi == 1) {
sonuc = ((100 + yuzde) * meblag) / 100;
_sonuc = sonuc;
print("_hesapYontemi: " + _hesapYontemi.toString());
print("_sonuc: " + _sonuc.toString());
return sonuc;
} else if (_hesapYontemi == 2) {
sonuc = ((100 - yuzde) * meblag) / 100;
_sonuc = sonuc;
print("_hesapYontemi: " + _hesapYontemi.toString());
print("_sonuc: " + _sonuc.toString());
return sonuc;
} else if (_hesapYontemi == 3) {
sonuc = (yuzde * meblag) / 100;
_sonuc = sonuc;
print("_hesapYontemi: " + _hesapYontemi.toString());
print("_sonuc: " + _sonuc.toString());
return sonuc;
} else {
print("------------Hesap yöntemi bulunamadı----------");
return null;
}
}
}
}
}
}
}
/*
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0)),
child: Center(
child: IconButton(
icon: Icon(Icons.add),
onPressed: () {
setState(() {
_hesapYontemi = 3;
});
},
),
),
),
*/
| 0 |
mirrored_repositories | mirrored_repositories/percentage-calculation-application/main.dart | import 'package:flutter/material.dart';
import 'package:yuzde_hesapla/home_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
home: MyHomePage(title: 'Yüzde Hesapla'),
);
}
}
| 0 |
mirrored_repositories/instagram_clone | mirrored_repositories/instagram_clone/lib/insta_bloc_observer.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/foundation.dart';
class InstaBlocObserver extends BlocObserver {
@override
void onEvent(Bloc bloc, Object? event) {
super.onEvent(bloc, event);
if (kDebugMode) {
print(event);
}
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
if (kDebugMode) {
print(error);
}
super.onError(bloc, error, stackTrace);
}
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
if (kDebugMode) {
print(change);
}
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
if (kDebugMode) {
print(transition);
}
}
}
| 0 |
mirrored_repositories/instagram_clone | mirrored_repositories/instagram_clone/lib/main.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:instagram_clone/firebase_options.dart';
import 'package:instagram_clone/pages/splash_screen/splash_screen.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/utility/firebase_messaging_service.dart';
import 'insta_bloc_observer.dart';
import 'pages/splash_screen/splash_cubit/splash_cubit.dart';
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin(); // instance of flutterLocalNotificationsPlugin
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@mipmap/notification_icon'); // for android
const DarwinInitializationSettings darwinInitializationSettings =
DarwinInitializationSettings(); // for iOS
InitializationSettings initializationSettings = const InitializationSettings(
android: androidInitializationSettings,
iOS: darwinInitializationSettings,
);
String? fcmToken = "";
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
await FirebaseMessagingService().initNotifications();
Bloc.observer = InstaBlocObserver();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Instagram',
theme: ThemeData(
primarySwatch: Colors.blue,
inputDecorationTheme: InputDecorationTheme(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(width: 1, color: Colors.white.withOpacity(0.2)),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(width: 1, color: Colors.white.withOpacity(0.2)),
),
),
),
home: BlocProvider(
create: (BuildContext context) => SplashCubit(),
child: const SplashScreen(),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/constants/colors.dart | import 'package:flutter/material.dart';
Color textFieldBackgroundColor = const Color(0xff121212);
Color instablue = const Color(0xff3797EF);
Color searchHintText = const Color(0xff8E8E93);
Color searchTextFieldColor = const Color(0xff262626);
Color profilePhotoBorder = const Color(0xff48484A);
Color instaRed = const Color(0xfffd1d1d);
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/instatext.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class InstaText extends StatelessWidget {
const InstaText(
{super.key,
required this.fontSize,
required this.color,
required this.fontWeight,
required this.text});
final double fontSize;
final Color color;
final FontWeight fontWeight;
final String text;
@override
Widget build(BuildContext context) {
return Text(
text,
style: GoogleFonts.sourceSansPro(
fontSize: fontSize,
fontWeight: fontWeight,
color: color,
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/insta_textfield.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class InstaTextField extends StatelessWidget {
const InstaTextField({
super.key,
this.controller,
required this.hintText,
required this.fontSize,
required this.color,
required this.fontWeight,
required this.hintColor,
required this.obscureText,
required this.icon,
required this.borderRadius,
required this.backgroundColor,
required this.forPassword,
required this.suffixIconCallback,
this.suffixIcon,
required this.editProfileTextfield,
required this.enabled,
required this.onChange,
this.focusNode,
});
final TextEditingController? controller;
final String hintText;
final double fontSize;
final Color color;
final Color hintColor;
final FontWeight fontWeight;
final bool obscureText;
final Widget? icon;
final double borderRadius;
final Color backgroundColor;
final bool forPassword;
final VoidCallback suffixIconCallback;
final Icon? suffixIcon;
final bool editProfileTextfield;
final bool enabled;
final Function(String value)? onChange;
final FocusNode? focusNode;
@override
Widget build(BuildContext context) {
return TextField(
focusNode: focusNode,
onChanged: onChange,
enabled: enabled,
cursorColor: Colors.white,
style: GoogleFonts.sourceSansPro(
fontSize: fontSize,
fontWeight: fontWeight,
color: color,
),
controller: controller,
obscureText: obscureText,
decoration: editProfileTextfield
? InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white.withOpacity(0.15)),
),
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
disabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white.withOpacity(0.15)),
),
)
: InputDecoration(
suffixIcon: forPassword
? IconButton(
icon: suffixIcon!,
onPressed: suffixIconCallback,
)
: const SizedBox(
height: 0,
width: 0,
),
contentPadding: const EdgeInsets.only(left: 8),
prefixIcon: icon,
isDense: true,
filled: true,
fillColor: backgroundColor,
hintText: hintText,
hintStyle: GoogleFonts.sourceSansPro(
fontSize: fontSize,
fontWeight: fontWeight,
color: hintColor,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(borderRadius),
borderSide: const BorderSide(width: 1, color: Colors.grey),
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/profile_widget.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone/constants/colors.dart';
class ProfileWidget extends StatelessWidget {
const ProfileWidget({
super.key,
required this.height,
required this.width,
required this.wantBorder,
required this.photoSelected,
required this.editProfileImage,
required this.url,
required this.loading,
});
final double height;
final double width;
final bool wantBorder;
final bool photoSelected;
final bool editProfileImage;
final String url;
final bool loading;
@override
Widget build(BuildContext context) {
if (kDebugMode) {
print(url);
}
return Container(
decoration: wantBorder
? BoxDecoration(
border: (editProfileImage && photoSelected)
? null
: Border.all(
color: editProfileImage
? profilePhotoBorder
: photoSelected
? Colors.white
: searchHintText,
width: 1.5),
shape: BoxShape.circle)
: null,
height: height,
width: width,
child: photoSelected
? ClipOval(
child: Container(
decoration: const BoxDecoration(shape: BoxShape.circle),
child: CachedNetworkImage(
height: 340,
width: 340,
fit: BoxFit.fill,
imageUrl: url,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
),
)
: loading
? const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
))
: Center(
child: Icon(
Icons.person,
color: searchHintText,
size: height * 0.3,
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/profile_photo.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone/constants/colors.dart';
class ProfilePhoto extends StatelessWidget {
const ProfilePhoto({
super.key,
required this.height,
required this.width,
required this.wantBorder,
required this.storyAdder,
required this.imageUrl,
});
final double height;
final double width;
final bool wantBorder;
final bool storyAdder;
final String imageUrl;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(5),
height: height,
width: width,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: wantBorder
? Border.all(
color: profilePhotoBorder,
)
: null,
),
child: storyAdder
? Center(
child: Container(
padding: const EdgeInsets.all(18),
child: Image.asset(
'assets/images/add_Chat.png',
),
),
)
: imageUrl != ""
? ClipOval(
child: Container(
decoration: const BoxDecoration(shape: BoxShape.circle),
child: CachedNetworkImage(
height: 340,
width: 340,
fit: BoxFit.fill,
imageUrl: imageUrl,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
),
)
: const CircleAvatar(
child: Icon(Icons.person),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/comment_list.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/data/comment_data.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/bloc/search_bloc.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CommentList extends StatelessWidget {
const CommentList({
super.key,
required this.comments,
required this.tileHeight,
required this.height,
required this.width,
required this.sharedPreferences,
required this.feedComments,
required this.searchComments,
required this.profileComments,
required this.postIndex,
required this.inFeed,
});
final List<Comments> comments;
final double tileHeight;
final double height;
final double width;
final SharedPreferences sharedPreferences;
final bool feedComments;
final bool searchComments;
final bool profileComments;
final int postIndex;
final bool inFeed;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: comments.length,
itemBuilder: (context, index) {
return SizedBox(
height: tileHeight,
width: double.infinity,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePhoto(
height: height * 0.06,
width: height * 0.065,
wantBorder: false,
storyAdder: false,
imageUrl: comments[index].profilePhotoUrl!,
),
SizedBox(
width: width * 0.03,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.w700,
text: comments[index].username!),
InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
text: comments[index].comment!),
],
),
],
),
index == 0 ||
(comments[index].userId !=
sharedPreferences.getString('userId'))
? Container()
: IconButton(
icon: const Icon(
Icons.delete_outline,
color: Colors.white,
),
onPressed: () {
if (feedComments) {
context.read<FeedBloc>().add(DeleteFeedComment(
postIndex,
index - 1,
inFeed,
));
} else if (searchComments) {
context.read<SearchBloc>().add(
DeleteSearchComment(postIndex, index - 1));
} else if (profileComments) {
context.read<ProfileBloc>().add(
DeleteProfileComment(postIndex, index - 1));
}
},
),
]),
);
});
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/user_posts.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/bloc/search_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/comment_page.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/post_tile.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../constants/colors.dart';
class UserPosts extends StatefulWidget {
const UserPosts({
super.key,
required this.inProfile,
required this.inFeed,
});
final bool inProfile;
final bool inFeed;
@override
State<UserPosts> createState() => _UserPostsState();
}
class _UserPostsState extends State<UserPosts> {
Widget buildBottomSheet(
BuildContext context,
double height,
double width,
bool inProfile,
bool userPosts,
int index,
SearchState? searchState,
ProfileState? profileState,
FeedState? feedState,
) {
return SizedBox(
height: height * 0.3,
child: Padding(
padding: const EdgeInsets.only(
top: 16.0,
bottom: 16.0,
),
child: Column(
children: [
GestureDetector(
onTap: () {
if (feedState != null) {
context.read<FeedBloc>().add(BookmarkFeed(index, false));
} else if (profileState != null) {
context.read<ProfileBloc>().add(BookmarkProfile(index));
} else {
context.read<SearchBloc>().add(BookmarkSearch(index));
}
Navigator.of(context).pop();
},
child: Column(
children: [
Container(
height: height * 0.09,
width: height * 0.09,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
width: 1,
),
),
child: Center(
child: feedState != null
? feedState.myData.bookmarks.contains(
feedState.userData.posts[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
size: 30,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
size: 30,
)
: profileState != null
? profileState.userData.bookmarks.contains(
profileState.userData.posts[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
size: 30,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
size: 30,
)
: searchState!.myData.bookmarks.contains(
searchState.usersPosts
? searchState
.userData.posts[index].id
: searchState.posts[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
size: 30,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
size: 30,
)),
),
const SizedBox(
height: 4.0,
),
const InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Save",
)
],
),
),
SizedBox(
height: height * 0.01,
),
Divider(
color: Colors.white.withOpacity(0.3),
),
(inProfile || userPosts)
? ListTile(
minLeadingWidth: 0,
leading: Icon(
Icons.delete_outline,
color: instaRed,
),
title: InstaText(
fontSize: 17,
color: instaRed,
fontWeight: FontWeight.normal,
text: "Delete",
),
onTap: () {
if (profileState != null) {
context.read<ProfileBloc>().add(DeletePost(index));
} else {
if (searchState!.usersPosts) {
context
.read<SearchBloc>()
.add(DeleteSearchProfilePost(index));
}
}
Navigator.of(context).pop();
},
)
: ListTile(
minLeadingWidth: 0,
leading: searchState!.myData.following
.contains(searchState.posts[index].userId)
? const Icon(
Icons.person_remove,
color: Colors.white,
)
: const Icon(
Icons.person_add,
color: Colors.white,
),
title: InstaText(
fontSize: 17,
color: Colors.white,
fontWeight: FontWeight.normal,
text: searchState.myData.following
.contains(searchState.posts[index].userId)
? "Unfollow"
: "follow",
),
onTap: () {
if (searchState.myData.following
.contains(searchState.posts[index].userId)) {
context.read<SearchBloc>().add(UnFollowSearchEvent(
fromProfile: false, index: index));
} else {
context.read<SearchBloc>().add(FollowSearchEvent(
fromProfile: false, index: index));
}
Navigator.of(context).pop();
},
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
leading: IconButton(
onPressed: () async {
if (widget.inFeed) {
var bloc = context.read<FeedBloc>();
bloc.pageController.jumpToPage(1);
} else {
if (widget.inProfile) {
var bloc = context.read<ProfileBloc>();
bloc.pageController.jumpToPage(0);
} else {
var bloc = context.read<SearchBloc>();
if (bloc.state.usersPosts) {
bloc.pageController.jumpToPage(0);
} else {
bloc.pageController.jumpToPage(1);
}
}
}
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
),
title: InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w700,
text: widget.inProfile && context.read<ProfileBloc>().state.savedPosts
? "Saved"
: (widget.inProfile ||
context.read<SearchBloc>().state.usersPosts ||
widget.inFeed)
? "Posts"
: "Explore",
),
),
body: widget.inFeed
? BlocBuilder<FeedBloc, FeedState>(
builder: (context, state) {
return ScrollablePositionedList.builder(
initialScrollIndex: state.postsIndex,
itemCount: state.userData.posts.length,
itemBuilder: (context, index) {
return PostTile(
isFeedData: false,
width: width,
height: height,
profileState: null,
searchState: null,
index: index,
feedState: state,
optionPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor: textFieldBackgroundColor,
context: context,
builder: (_) => BlocProvider.value(
value: context.read<ProfileBloc>(),
child: buildBottomSheet(
context,
height,
width,
widget.inProfile,
false,
index,
null,
null,
state),
));
},
likePressed: () {
context.read<FeedBloc>().add(PostLikeEvent(
state.userData.posts[index].id,
index,
state.userData.posts[index].userId,
false,
));
},
onDoubleTap: () {
context.read<FeedBloc>().add(PostLikeEvent(
state.userData.posts[index].id,
index,
state.userData.posts[index].userId,
false,
));
},
commentPressed: () async {
var sharedPreferences =
await SharedPreferences.getInstance();
if (mounted) {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<FeedBloc>(),
child: CommentPage(
sharedPreferences: sharedPreferences,
postIndex: index,
profileState: null,
searchState: null,
feedState: state,
inFeed: false,
),
)));
}
},
bookmarkPressed: () {
context
.read<FeedBloc>()
.add(BookmarkFeed(index, false));
},
sharePressed: () async {
context.read<FeedBloc>().add(ShareFileEvent(
caption: state.userData.posts[index].caption,
imageUrl: state.userData.posts[index].imageUrl));
await Fluttertoast.showToast(
msg: "Please wait !!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.white,
textColor: Colors.black,
fontSize: 14.0);
},
onUserNamePressed: () {},
);
},
);
},
)
: widget.inProfile
? BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is ProfileLoading) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
} else {
return ScrollablePositionedList.builder(
initialScrollIndex:
state.savedPosts ? 0 : state.postsIndex,
itemCount: state.savedPosts
? state.savedPostsList.length
: state.userData.posts.length,
itemBuilder: (context, index) {
return PostTile(
isFeedData: false,
width: width,
height: height,
profileState: state,
searchState: null,
index: index,
feedState: null,
optionPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor: textFieldBackgroundColor,
context: context,
builder: (_) => BlocProvider.value(
value: context.read<ProfileBloc>(),
child: buildBottomSheet(
context,
height,
width,
widget.inProfile,
false,
index,
null,
state,
null,
),
));
},
likePressed: () {
context
.read<ProfileBloc>()
.add(LikePostEvent(index));
},
onDoubleTap: () {
context
.read<ProfileBloc>()
.add(LikePostEvent(index));
},
commentPressed: () async {
var sharedPreferences =
await SharedPreferences.getInstance();
if (mounted) {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<ProfileBloc>(),
child: CommentPage(
sharedPreferences:
sharedPreferences,
postIndex: index,
profileState: state,
searchState: null,
feedState: null,
inFeed: false,
),
)));
}
},
bookmarkPressed: () {
context
.read<ProfileBloc>()
.add(BookmarkProfile(index));
},
sharePressed: () async {
context.read<ProfileBloc>().add(
ShareProfileFileEvent(
imageUrl:
state.savedPosts
? state.savedPostsList[index]
.imageUrl
: state.userData.posts[index]
.imageUrl,
caption: state.savedPosts
? state.savedPostsList[index].caption
: state
.userData.posts[index].caption));
await Fluttertoast.showToast(
msg: "Please wait !!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.white,
textColor: Colors.black,
fontSize: 14.0);
},
onUserNamePressed: () {},
);
},
);
}
},
)
: BlocBuilder<SearchBloc, SearchState>(
builder: (context, state) {
return ScrollablePositionedList.builder(
initialScrollIndex: state.postsIndex,
itemCount: state.usersPosts
? state.userData.posts.length
: state.posts.length,
itemBuilder: (context, index) {
return PostTile(
isFeedData: false,
width: width,
height: height,
profileState: null,
searchState: state,
index: index,
feedState: null,
optionPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor: textFieldBackgroundColor,
context: context,
builder: (_) => BlocProvider.value(
value: context.read<SearchBloc>(),
child: buildBottomSheet(
context,
height,
width,
widget.inProfile,
state.usersPosts,
index,
state,
null,
null),
));
},
likePressed: () {
context.read<SearchBloc>().add(SearchLikePostEvent(
index,
state.usersPosts,
state.usersPosts
? state.userData.id
: state.posts[index].userId,
state.usersPosts
? state.userData.posts[index].id
: state.posts[index].id));
},
commentPressed: () async {
var sharedPreferences =
await SharedPreferences.getInstance();
if (mounted) {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<SearchBloc>(),
child: CommentPage(
sharedPreferences: sharedPreferences,
postIndex: index,
searchState: state,
profileState: null,
feedState: null,
inFeed: false,
),
)));
}
},
bookmarkPressed: () {
context
.read<SearchBloc>()
.add(BookmarkSearch(index));
},
sharePressed: () async {
context.read<SearchBloc>().add(ShareSearchFileEvent(
caption: state.usersPosts
? state.userData.posts[index].caption
: state.posts[index].caption,
imageUrl: state.usersPosts
? state.userData.posts[index].imageUrl
: state.posts[index].imageUrl));
await Fluttertoast.showToast(
msg: "Please wait !!!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.white,
textColor: Colors.black,
fontSize: 14.0);
},
onDoubleTap: () {
context.read<SearchBloc>().add(SearchLikePostEvent(
index,
state.usersPosts,
state.usersPosts
? state.userData.id
: state.posts[index].userId,
state.usersPosts
? state.userData.posts[index].id
: state.posts[index].id));
},
onUserNamePressed: () async {
if (!state.usersPosts) {
var bloc = context.read<SearchBloc>();
bloc.add(FetchUserDataInSearch(
userId: state.posts[index].userId));
await bloc.pageController.animateToPage(0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeIn);
}
},
);
},
);
},
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/post_tile.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
import '../pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import '../pages/homepage/homepage_pages/search/bloc/search_bloc.dart';
class PostTile extends StatelessWidget {
const PostTile({
super.key,
required this.width,
required this.height,
required this.profileState,
required this.searchState,
required this.index,
required this.feedState,
required this.optionPressed,
required this.likePressed,
required this.commentPressed,
required this.bookmarkPressed,
required this.sharePressed,
required this.onDoubleTap,
required this.onUserNamePressed,
required this.isFeedData,
});
final double width;
final double height;
final ProfileState? profileState;
final SearchState? searchState;
final FeedState? feedState;
final int index;
final VoidCallback optionPressed;
final VoidCallback likePressed;
final VoidCallback commentPressed;
final VoidCallback bookmarkPressed;
final VoidCallback sharePressed;
final VoidCallback onDoubleTap;
final VoidCallback onUserNamePressed;
final bool isFeedData;
@override
Widget build(BuildContext context) {
var homePageBloc = context.read<HomepageBloc>();
return SizedBox(
height: height - 2.5 * (AppBar().preferredSize.height),
width: width,
child: Column(
children: [
SizedBox(
height: AppBar().preferredSize.height,
width: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: ProfilePhoto(
height: height * 0.06,
width: height * 0.065,
wantBorder: false,
storyAdder: false,
imageUrl: searchState == null
? profileState == null
? isFeedData
? feedState!
.posts[index].userProfilePhotoUrl
: feedState!.userData.posts[index]
.userProfilePhotoUrl
: profileState!.savedPosts
? profileState!.savedPostsList[index]
.userProfilePhotoUrl
: profileState!.userData.profilePhotoUrl
: searchState!.usersPosts
? searchState!.userData.profilePhotoUrl
: searchState!
.posts[index].userProfilePhotoUrl),
),
SizedBox(
width: width * 0.02,
),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
child: GestureDetector(
onTap: onUserNamePressed,
child: InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.w700,
text: searchState == null
? profileState == null
? isFeedData
? feedState!.posts[index].username
: feedState!
.userData.posts[index].username
: profileState!.savedPosts
? profileState!
.savedPostsList[index].username
: profileState!.userData.username
: searchState!.usersPosts
? searchState!.userData.username
: searchState!.posts[index].username,
),
),
)
],
),
IconButton(
onPressed: optionPressed,
icon: const Icon(
Icons.more_vert,
color: Colors.white,
),
),
],
),
),
Expanded(
child: GestureDetector(
onDoubleTap: onDoubleTap,
child: CachedNetworkImage(
width: double.infinity,
imageUrl: searchState == null
? profileState == null
? isFeedData
? feedState!.posts[index].imageUrl
: feedState!.userData.posts[index].imageUrl
: profileState!.savedPosts
? profileState!.savedPostsList[index].imageUrl
: profileState!.userData.posts[index].imageUrl
: searchState!.usersPosts
? searchState!.userData.posts[index].imageUrl
: searchState!.posts[index].imageUrl,
fit: BoxFit.fill,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
height: height * 0.054,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
IconButton(
icon: searchState != null
? searchState!.usersPosts
? searchState!.userData.posts[index].likes
.contains(homePageBloc.sharedPreferences
.getString("userId"))
? Image.asset(
"assets/images/notification_red.png",
)
: Image.asset(
"assets/images/notification.png",
)
: searchState!.posts[index].likes.contains(homePageBloc.sharedPreferences
.getString("userId"))
? Image.asset(
"assets/images/notification_red.png",
)
: Image.asset(
"assets/images/notification.png",
)
: profileState != null
? profileState!.savedPosts
? profileState!.savedPostsList[index].likes
.contains(homePageBloc.sharedPreferences
.getString("userId"))
? Image.asset(
"assets/images/notification_red.png",
)
: Image.asset(
"assets/images/notification.png",
)
: profileState!.userData.posts[index].likes
.contains(homePageBloc.sharedPreferences
.getString("userId"))
? Image.asset(
"assets/images/notification_red.png",
)
: Image.asset(
"assets/images/notification.png",
)
: feedState != null
? (isFeedData
? feedState!.posts[index].likes.contains(homePageBloc.sharedPreferences.getString("userId"))
: feedState!.userData.posts[index].likes.contains(homePageBloc.sharedPreferences.getString("userId")))
? Image.asset(
"assets/images/notification_red.png",
)
: Image.asset(
"assets/images/notification.png",
)
: Image.asset(
"assets/images/notification.png",
),
onPressed: likePressed,
),
IconButton(
icon: Image.asset(
"assets/images/insta_comment.png",
),
onPressed: commentPressed,
),
IconButton(
icon: Image.asset(
"assets/images/messanger.png",
),
onPressed: sharePressed,
),
],
),
IconButton(
onPressed: bookmarkPressed,
icon: feedState != null
? (isFeedData
? feedState!.myData.bookmarks
.contains(feedState!.posts[index].id)
: feedState!.myData.bookmarks.contains(
feedState!.userData.posts[index].id))
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
)
: profileState != null
? profileState!.savedPosts
? profileState!.userData.bookmarks.contains(
profileState!.savedPostsList[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
)
: profileState!.userData.bookmarks.contains(
profileState!.userData.posts[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
)
: searchState != null
? searchState!.myData.bookmarks.contains(
searchState!.usersPosts
? searchState!
.userData.posts[index].id
: searchState!.posts[index].id)
? const Icon(
CupertinoIcons.bookmark_fill,
color: Colors.white,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
)
: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
),
),
],
),
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Align(
alignment: Alignment.centerLeft,
child: InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w700,
text: searchState == null
? profileState == null
? isFeedData
? "${feedState!.posts[index].likes.length} likes"
: "${feedState!.userData.posts[index].likes.length} likes"
: profileState!.savedPosts
? "${profileState!.savedPostsList[index].likes.length} likes"
: "${profileState!.userData.posts[index].likes.length} likes"
: searchState!.usersPosts
? "${searchState!.userData.posts[index].likes.length} likes"
: "${searchState!.posts[index].likes.length} likes",
),
),
),
SizedBox(
height: height * 0.005,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Align(
alignment: Alignment.centerLeft,
child: Row(
children: [
InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w700,
text: searchState == null
? profileState == null
? isFeedData
? feedState!.posts[index].username
: feedState!.userData.posts[index].username
: profileState!.savedPosts
? profileState!.savedPostsList[index].username
: profileState!.userData.username
: searchState!.usersPosts
? searchState!.userData.username
: searchState!.posts[index].username,
),
SizedBox(
width: width * 0.02,
),
InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
text: searchState == null
? profileState == null
? isFeedData
? feedState!.posts[index].caption
: feedState!.userData.posts[index].caption
: profileState!.savedPosts
? profileState!.savedPostsList[index].caption
: profileState!.userData.posts[index].caption
: searchState!.usersPosts
? searchState!.userData.posts[index].caption
: searchState!.posts[index].caption,
),
],
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/insta_button.dart | import 'package:flutter/material.dart';
import 'package:instagram_clone/widgets/instatext.dart';
class InstaButton extends StatelessWidget {
const InstaButton({
super.key,
required this.onPressed,
required this.text,
required this.fontSize,
required this.textColor,
required this.fontWeight,
required this.buttonColor,
required this.height,
required this.postButton,
required this.width,
required this.borderWidth,
this.buttonIcon,
});
final VoidCallback onPressed;
final String text;
final double fontSize;
final Color textColor;
final Color buttonColor;
final FontWeight fontWeight;
final double height;
final bool postButton;
final double width;
final double borderWidth;
final Icon? buttonIcon;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
side: buttonColor == Colors.black
? BorderSide(
width: borderWidth,
color: postButton
? Colors.white
: Colors.white.withOpacity(0.15))
: null,
backgroundColor: buttonColor,
minimumSize: Size(width, height),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InstaText(
fontSize: fontSize,
color: textColor,
fontWeight: fontWeight,
text: text),
buttonIcon != null
? SizedBox(
width: width * 0.05,
)
: Container(),
buttonIcon ?? Container(),
],
));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/notification_tile.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
class NotificationTile extends StatelessWidget {
const NotificationTile(
{super.key,
required this.profilePhotoUrl,
required this.username,
required this.dateTime,
required this.message,
required this.imageUrl,
required this.height,
required this.width});
final String profilePhotoUrl;
final String username;
final String dateTime;
final String message;
final String? imageUrl;
final double height;
final double width;
@override
Widget build(BuildContext context) {
return Container(
height: height,
width: width,
decoration: const BoxDecoration(color: Colors.black),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePhoto(
height: height * 0.8,
width: width * 0.16,
wantBorder: false,
storyAdder: false,
imageUrl: profilePhotoUrl),
SizedBox(
width: width * 0.6,
child: RichText(
text: TextSpan(
text: username,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(
text: '$message. ',
style: const TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal)),
TextSpan(
text: dateTime,
style: TextStyle(
fontSize: 16,
color: Colors.white.withOpacity(0.6),
fontWeight: FontWeight.normal)),
],
),
),
),
],
),
imageUrl != null
? SizedBox(
height: height * 0.7,
width: height * 0.7,
child: CachedNetworkImage(
fit: BoxFit.fill,
imageUrl: imageUrl!,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
))
: Container()
],
));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/widgets/insta_snackbar.dart | import 'package:flutter/material.dart';
import 'package:instagram_clone/widgets/instatext.dart';
class InstaSnackbar {
const InstaSnackbar({
required this.text,
});
final String text;
void show(BuildContext context) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
backgroundColor: Colors.white,
duration: const Duration(seconds: 2),
content: InstaText(
fontSize: 14,
color: Colors.black,
fontWeight: FontWeight.w500,
text: text),
));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/feed.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/notification/bloc/notification_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/notification/notification.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/posts/post.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/search_page.dart';
import 'package:instagram_clone/widgets/profile_widget.dart';
import '../../constants/colors.dart';
import 'homepage_pages/profile/profile.dart';
import 'homepage_pages/search/bloc/search_bloc.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List pages = [
const FeedPage(),
const SearchPage(),
const PostPage(),
const NotificationPage(),
const ProfilePage()
];
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return WillPopScope(
onWillPop: () async {
var searchBlocState = context.read<SearchBloc>().state;
var homePageBlocState = context.read<HomepageBloc>().state;
var profileBloc = context.read<ProfileBloc>();
if (homePageBlocState.index == 0) {
var bloc = context.read<FeedBloc>();
if (bloc.pageController.page == 2) {
bloc.pageController.jumpToPage(1);
return false;
} else if (bloc.pageController.page == 1) {
bloc.add(const GetFeed(false));
bloc.pageController.jumpTo(0);
return false;
} else {
return true;
}
} else if (homePageBlocState.index == 1) {
var bloc = context.read<SearchBloc>();
if (bloc.pageController.page == 0 &&
searchBlocState.previousPage == 1) {
bloc.pageController.jumpToPage(1);
bloc.add(UserProfileBackEvent());
} else if (bloc.pageController.page == 0 &&
searchBlocState.previousPage == 2) {
bloc.pageController.jumpToPage(1);
bloc.add(GetPosts());
} else if (searchBlocState is UsersSearched) {
context.read<SearchBloc>().searchController.clear();
context.read<SearchBloc>().focusNode.unfocus();
context.read<SearchBloc>().add(GetPosts());
} else if (bloc.pageController.page == 2 && bloc.state.usersPosts) {
bloc.pageController.jumpToPage(0);
} else if (bloc.pageController.page == 2 && !bloc.state.usersPosts) {
bloc.pageController.jumpToPage(1);
} else if (bloc.pageController.page == 1 ||
searchBlocState is PostsFetched) {
context.read<HomepageBloc>().add(TabChange(0));
context.read<FeedBloc>().add(const GetFeed(false));
}
return false;
} else if (homePageBlocState.index == 2) {
context.read<HomepageBloc>().add(TabChange(0));
context.read<FeedBloc>().add(const GetFeed(false));
return false;
} else if (homePageBlocState.index == 3) {
context.read<HomepageBloc>().add(TabChange(0));
context.read<FeedBloc>().add(const GetFeed(false));
return false;
} else if (homePageBlocState.index == 4) {
if (profileBloc.pageController.page == 1) {
profileBloc.pageController.jumpToPage(0);
} else {
context.read<HomepageBloc>().add(TabChange(0));
context.read<FeedBloc>().add(const GetFeed(false));
}
return false;
} else {
return true;
}
},
child: Scaffold(
backgroundColor: Colors.black,
body: BlocBuilder<HomepageBloc, HomepageState>(
builder: (context, state) {
if (state is HomePageLoadingState) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
} else {
return pages[state.index];
}
},
),
bottomNavigationBar:
BlocBuilder<HomepageBloc, HomepageState>(builder: (context, state) {
if (state is HomePageLoadingState) {
return Container();
} else {
return BottomNavigationBar(
elevation: 0,
currentIndex: state.index,
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.fixed,
backgroundColor: textFieldBackgroundColor,
items: [
BottomNavigationBarItem(
icon: SizedBox(
// height: height * 0.05,
width: width * 0.065,
child: state.index == 0
? Image.asset('assets/images/home_filled.png')
: Image.asset('assets/images/home.png'),
),
label: "Home"),
BottomNavigationBarItem(
icon: SizedBox(
// height: height * 0.05,
width: width * 0.065,
child: state.index == 1
? Image.asset(
'assets/images/search_insta_filled.png')
: Image.asset('assets/images/search_insta.png')),
label: "Search"),
BottomNavigationBarItem(
icon: SizedBox(
// height: height * 0.05,
width: width * 0.065,
child: Image.asset('assets/images/post.png')),
label: "Post"),
BottomNavigationBarItem(
icon: Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
// height: height * 0.05,
width: state.newNotifications
? width * 0.055
: width * 0.065,
child: state.index == 3
? Image.asset(
'assets/images/notification_filled.png')
: Image.asset('assets/images/notification.png'),
),
SizedBox(
height: state.newNotifications ? 3 : 0,
),
Container(
height: state.newNotifications ? 3 : 0,
width: state.newNotifications ? 3 : 0,
decoration: const BoxDecoration(
shape: BoxShape.circle, color: Colors.white),
)
],
),
),
label: "Notification"),
BottomNavigationBarItem(
icon: ProfileWidget(
url: context
.read<HomepageBloc>()
.sharedPreferences
.getString("profilePhotoUrl")!,
height: height * 0.035,
width: height * 0.035,
wantBorder: state.index == 4 ? true : false,
photoSelected: true,
editProfileImage: false,
loading: false,
),
label: "Profile"),
],
onTap: (index) async {
var homePageBloc = context.read<HomepageBloc>();
homePageBloc.add(TabChange(index));
if (index == 0) {
if (homePageBloc.state.index != 0) {
context.read<FeedBloc>().add(const GetFeed(false));
}
} else if (index == 1) {
var bloc = context.read<SearchBloc>();
if (homePageBloc.state.index != 1) {
bloc.add(GetPosts());
}
bloc.searchController.clear();
if (bloc.pageController.page == 1) {
await bloc.pageController.animateToPage(
0,
duration: const Duration(microseconds: 200),
curve: Curves.ease,
);
}
} else if (index == 3) {
context.read<HomepageBloc>().add(SeenNewNotification());
context.read<NotificationBloc>().add(FetchNotifications());
} else if (index == 4) {
context.read<ProfileBloc>().add(GetUserDetails());
}
},
);
}
}),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage | mirrored_repositories/instagram_clone/lib/pages/homepage/bloc/homepage_state.dart | part of 'homepage_bloc.dart';
@immutable
abstract class HomepageState extends Equatable {
final int index;
final bool newNotifications;
const HomepageState(this.index, this.newNotifications);
@override
List<Object?> get props => [index, newNotifications];
}
class HomepageInitial extends HomepageState {
const HomepageInitial(super.index, super.newNotifications);
@override
List<Object?> get props => [index, newNotifications];
}
class TabChanged extends HomepageState {
const TabChanged(super.index, super.newNotifications);
@override
List<Object?> get props => [index, newNotifications];
}
class HomePageLoadingState extends HomepageState {
const HomePageLoadingState(super.index, super.newNotifications);
@override
List<Object?> get props => [index, newNotifications];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage | mirrored_repositories/instagram_clone/lib/pages/homepage/bloc/homepage_event.dart | part of 'homepage_bloc.dart';
@immutable
abstract class HomepageEvent extends Equatable {
@override
List<Object?> get props => [];
}
class TabChange extends HomepageEvent {
final int index;
TabChange(this.index);
@override
List<Object?> get props => [index];
}
class GetDetails extends HomepageEvent {}
class RefreshUi extends HomepageEvent {
final String imageUrl;
RefreshUi(this.imageUrl);
@override
List<Object?> get props => [imageUrl];
}
class SeenNewNotification extends HomepageEvent {}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage | mirrored_repositories/instagram_clone/lib/pages/homepage/bloc/homepage_bloc.dart | import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'homepage_event.dart';
part 'homepage_state.dart';
class HomepageBloc extends Bloc<HomepageEvent, HomepageState> {
HomepageBloc() : super(const HomePageLoadingState(0, false)) {
on<TabChange>(
(event, emit) => emit(TabChanged(event.index, state.newNotifications)));
on<GetDetails>((event, emit) => getDetails(event, emit));
on<RefreshUi>((event, emit) =>
emit(HomepageInitial(state.index, state.newNotifications)));
on<SeenNewNotification>(
(event, emit) => setNewNotificationsStatus(event, emit));
}
late final SharedPreferences sharedPreferences;
Future<void> setNewNotificationsStatus(
SeenNewNotification event, Emitter emit) async {
String? userId = sharedPreferences.getString("userId");
if (state.newNotifications) {
await FirebaseFirestore.instance
.collection("notifications")
.doc(userId)
.update({"new_notifications": false});
emit(HomepageInitial(state.index, false));
}
}
Future<void> getDetails(GetDetails event, Emitter emit) async {
sharedPreferences = await SharedPreferences.getInstance();
var userId = sharedPreferences.getString("userId");
var collectionRef = FirebaseFirestore.instance.collection("notifications");
var notificationData = await collectionRef.doc(userId).get();
bool newNotifications = false;
if (notificationData.data() == null) {
await collectionRef
.doc(userId)
.set({"notifications": [], "new_notifications": false});
} else {
newNotifications = notificationData.data()!['new_notifications'];
}
emit(HomepageInitial(state.index, newNotifications));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification/notification.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/constants/colors.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/notification/bloc/notification_bloc.dart';
import 'package:instagram_clone/widgets/notification_tile.dart';
class NotificationPage extends StatelessWidget {
const NotificationPage({super.key});
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
elevation: 0,
backgroundColor: textFieldBackgroundColor,
title: SizedBox(
height: AppBar().preferredSize.height * 0.8,
width: width * 0.3,
child: Image.asset('assets/images/instagram.png'),
)),
body: BlocBuilder<NotificationBloc, NotificationState>(
builder: (context, state) {
if (state is NotificationsInitialState) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
} else {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
physics: const ClampingScrollPhysics(),
itemCount: state.notifications.length,
itemBuilder: (context, index) {
String dateTime = "";
int inDays = DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inDays;
int inHours = DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inHours;
int inMinutes = DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inMinutes;
int inSeconds = DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inSeconds;
if (inDays > 0) {
dateTime = '${inDays}d ';
} else if (inHours > 0) {
dateTime = '${inHours}hr ';
} else if (inMinutes > 0) {
dateTime = '${inMinutes}m ';
} else if (inSeconds > 0) {
dateTime = '${inSeconds}s ';
}
if (kDebugMode) {
print(DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inHours);
print(DateTime.now()
.difference(
DateTime.parse(state.notifications[index].dateTime))
.inMinutes);
}
return NotificationTile(
imageUrl: state.notifications[index].imageUrl == ""
? null
: state.notifications[index].imageUrl,
profilePhotoUrl:
state.notifications[index].userProfilePhoto,
username:
state.notifications[index].message.split(" ")[0],
dateTime: dateTime,
message: state.notifications[index].message.substring(
state.notifications[index].message
.split(" ")[0]
.length),
height: height * 0.1,
width: width);
}),
);
}
}),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification/bloc/notification_event.dart | part of 'notification_bloc.dart';
abstract class NotificationEvent extends Equatable {
const NotificationEvent();
@override
List<Object> get props => [];
}
class FetchNotifications extends NotificationEvent {}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification/bloc/notification_bloc.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:instagram_clone/data/notification_data.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'notification_event.dart';
part 'notification_state.dart';
class NotificationBloc extends Bloc<NotificationEvent, NotificationState> {
NotificationBloc() : super(const NotificationsInitialState([])) {
on<FetchNotifications>((event, emit) => fetchNotifications(event, emit));
}
Future<void> fetchNotifications(
FetchNotifications event, Emitter emit) async {
emit(const NotificationsInitialState([]));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
var collectionRef = FirebaseFirestore.instance.collection("notifications");
var snapshots = await collectionRef.doc(userId).get();
if (snapshots.data() == null) {
emit(const NotificationsFetchedState([]));
await collectionRef
.doc(userId)
.set({"notifications": [], "new_notifications": false});
} else {
List data = snapshots.data()!["notifications"];
List<NotificationData> notifications = List.generate(data.length,
(index) => NotificationData.fromJson(data[data.length - 1 - index]));
emit(NotificationsFetchedState(notifications));
}
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/notification/bloc/notification_state.dart | part of 'notification_bloc.dart';
abstract class NotificationState extends Equatable {
const NotificationState(this.notifications);
final List<NotificationData> notifications;
@override
List<Object> get props => [notifications];
}
class NotificationsInitialState extends NotificationState {
const NotificationsInitialState(super.notifications);
@override
List<Object> get props => [notifications];
}
class NotificationsFetchedState extends NotificationState {
const NotificationsFetchedState(super.notifications);
@override
List<Object> get props => [notifications];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts/post.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/constants/colors.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/widgets/insta_button.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import '../../../../widgets/instatext.dart';
import 'bloc/posts_bloc.dart';
class PostPage extends StatefulWidget {
const PostPage({super.key});
@override
State<PostPage> createState() => _PostPageState();
}
class _PostPageState extends State<PostPage> {
final TextEditingController captionController = TextEditingController();
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
elevation: 0,
backgroundColor: textFieldBackgroundColor,
title: SizedBox(
height: AppBar().preferredSize.height * 0.8,
width: width * 0.3,
child: Image.asset('assets/images/instagram.png'),
)),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: BlocBuilder<PostsBloc, PostsState>(
builder: (context, state) {
if (state is PostsInitial) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "Post on Instagram",
),
SizedBox(
height: height * 0.05,
),
InstaButton(
borderWidth: 1,
width: width,
postButton: true,
onPressed: () {
context
.read<PostsBloc>()
.add(const ChooseImage(fromCamera: true));
},
text: "From Camera",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700,
buttonColor: Colors.black,
height: height * 0.08,
buttonIcon: const Icon(Icons.camera_alt_outlined),
),
SizedBox(
height: height * 0.05,
),
InstaButton(
borderWidth: 1,
width: width,
postButton: true,
onPressed: () {
context
.read<PostsBloc>()
.add(const ChooseImage(fromCamera: false));
},
text: "From Gallery",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700,
buttonColor: Colors.black,
height: height * 0.08,
buttonIcon: const Icon(CupertinoIcons.photo_fill),
)
],
);
} else if (state is PostReady) {
return Column(
children: [
Expanded(
child: Image.file(
File(state.imagePath),
),
),
SizedBox(
height: height * 0.04,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: captionController,
hintText: "Post Caption",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
onChange: (value) {},
),
SizedBox(
height: height * 0.04,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InstaButton(
borderWidth: 1,
width: width * 0.4,
onPressed: () {
context.read<PostsBloc>().add(CancelEvent());
},
text: "Cancel",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700,
buttonColor: Colors.black,
height: height * 0.05,
postButton: true),
SizedBox(
width: width * 0.01,
),
InstaButton(
borderWidth: 1,
width: width * 0.4,
onPressed: () {
String caption = captionController.text;
String userProfilePhotoUrl = context
.read<HomepageBloc>()
.sharedPreferences
.getString("profilePhotoUrl")!;
context
.read<PostsBloc>()
.add(PostImage(caption, userProfilePhotoUrl));
},
text: "Post",
fontSize: 14,
textColor: Colors.black,
fontWeight: FontWeight.w700,
buttonColor: Colors.white,
height: height * 0.05,
postButton: true),
],
)
],
);
} else if (state is PostingImageState) {
return Column(
children: [
Expanded(
child: Image.file(
File(state.imagePath),
),
),
SizedBox(
height: height * 0.04,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: captionController,
hintText: "Post Caption",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
onChange: (value) {},
),
SizedBox(
height: height * 0.04,
),
const Align(
alignment: Alignment.center,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
),
],
);
} else {
return Container();
}
},
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts/bloc/posts_bloc.dart | import 'dart:io';
import 'dart:math';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_clone/data/posts_data.dart';
import 'package:instagram_clone/data/user_data.dart';
import 'package:instagram_clone/main.dart';
import 'package:instagram_clone/utility/notification_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
part 'posts_event.dart';
part 'posts_state.dart';
class PostsBloc extends Bloc<PostsEvent, PostsState> {
PostsBloc() : super(const PostsInitial("")) {
on<ChooseImage>((event, emit) => chooseImage(event, emit));
on<CancelEvent>((event, emit) => emit(const PostsInitial("")));
on<PostImage>((event, emit) => postImage(event, emit));
}
Future<void> chooseImage(ChooseImage event, Emitter emit) async {
var image = await ImagePicker().pickImage(
source: event.fromCamera ? ImageSource.camera : ImageSource.gallery);
if (image != null) {
emit(PostReady(image.path));
} else {
emit(const PostsInitial(""));
}
}
Future<void> postImage(PostImage event, Emitter emit) async {
int id = Random().nextInt(100000);
try {
emit(PostingImageState(state.imagePath));
await sendNotification(id);
var sharedPreferences = await SharedPreferences.getInstance();
var userId = sharedPreferences.getString('userId');
var caption = event.caption;
var fireStoreCollectionRef =
FirebaseFirestore.instance.collection("users");
var userDocumentData = await fireStoreCollectionRef.doc(userId).get();
UserData userData = UserData.fromJson(userDocumentData.data()!);
String username = userData.username;
var fireStorageRef = FirebaseStorage.instance.ref();
Reference childRef = fireStorageRef.child(userId!);
var hash = const Uuid().v4();
String imageName = "posts/post$hash.jpg";
var imageLocationRef = childRef.child(imageName);
File image = File(state.imagePath);
await imageLocationRef.putFile(image);
var imageUrl = await imageLocationRef.getDownloadURL();
String postId = const Uuid().v4();
Post post = Post(
id: postId,
username: username,
imageUrl: imageUrl,
likes: [],
comments: [],
caption: caption,
userId: userId,
userProfilePhotoUrl: event.userProfilePhotoUrl);
List<Post> posts = userData.posts;
List newPosts = posts.map((post) => post.toJson()).toList();
newPosts.add(post.toJson());
await fireStoreCollectionRef.doc(userId).update({"posts": newPosts});
flutterLocalNotificationsPlugin.cancel(id);
emit(const PostsInitial(""));
String title = "New Post";
String notificationImageUrl = "";
String body = "$username just posted a photo";
var snapshots = await FirebaseFirestore.instance
.collection("users")
.where("following", arrayContains: userId)
.where("id", isNotEqualTo: userId)
.get();
List receiverFcmToken = List.generate(snapshots.docs.length,
(index) => snapshots.docs[index].data()['fcmToken']);
await NotificationService().sendNotification(
title, notificationImageUrl, body, receiverFcmToken, true);
} catch (e) {
if (kDebugMode) {
print(e);
}
flutterLocalNotificationsPlugin.cancel(id);
emit(const PostsInitial(""));
}
}
Future sendNotification(int id) async {
AndroidNotificationDetails androidNotificationDetails =
const AndroidNotificationDetails(
"Instagram Channel Id",
"Instagram Channel name",
importance: Importance.max,
priority: Priority.max,
onlyAlertOnce: true,
enableVibration: true,
playSound: true,
showProgress: true,
category: AndroidNotificationCategory.progress,
indeterminate: true,
);
DarwinNotificationDetails darwinNotificationDetails =
const DarwinNotificationDetails();
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails, iOS: darwinNotificationDetails);
await flutterLocalNotificationsPlugin.show(
id, "Posting...", "", notificationDetails);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts/bloc/posts_event.dart | part of 'posts_bloc.dart';
abstract class PostsEvent extends Equatable {
const PostsEvent();
@override
List<Object> get props => [];
}
class ChooseImage extends PostsEvent {
final bool fromCamera;
const ChooseImage({required this.fromCamera});
@override
List<Object> get props => [fromCamera];
}
class CancelEvent extends PostsEvent {}
class PostImage extends PostsEvent {
final String caption;
final String userProfilePhotoUrl;
const PostImage(this.caption, this.userProfilePhotoUrl);
@override
List<Object> get props => [caption, userProfilePhotoUrl];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/posts/bloc/posts_state.dart | part of 'posts_bloc.dart';
abstract class PostsState extends Equatable {
final String imagePath;
const PostsState(this.imagePath);
@override
List<Object> get props => [imagePath];
}
class PostsInitial extends PostsState {
const PostsInitial(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class PostReady extends PostsState {
const PostReady(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class PostDone extends PostsState {
const PostDone(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class PostingImageState extends PostsState {
const PostingImageState(super.imagePath);
@override
List<Object> get props => [imagePath];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/profile.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/constants/colors.dart';
import 'package:instagram_clone/pages/authentication/auth_pages/loginpage.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/story/bloc/story_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/story/view_story.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/edit_profile.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/previous_stories.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/bloc/search_bloc.dart'
as s;
import 'package:instagram_clone/widgets/user_posts.dart';
import 'package:instagram_clone/widgets/insta_button.dart';
import 'package:instagram_clone/widgets/insta_snackbar.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
import '../../../../data/user_data.dart';
import '../../../authentication/bloc/auth_bloc.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage>
with SingleTickerProviderStateMixin {
late final TabController tabController;
@override
void initState() {
super.initState();
tabController = TabController(length: 2, vsync: this);
}
Widget buildModelBottomSheet(
BuildContext context, double height, double width) {
var bloc = context.read<ProfileBloc>();
return SizedBox(
height: height * 0.3,
child: Padding(
padding: EdgeInsets.fromLTRB(width * 0.05, 8.0, width * 0.05, 8.0),
child: Column(
children: [
SizedBox(
height: height * 0.02,
),
ListTile(
minLeadingWidth: 0,
contentPadding: EdgeInsets.zero,
leading: const Icon(
CupertinoIcons.bookmark,
color: Colors.white,
),
title: const InstaText(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Saved"),
onTap: () async {
var bloc = context.read<ProfileBloc>();
Navigator.of(context).pop();
bloc.add(ShowSavedPosts());
await bloc.pageController.animateToPage(
1,
duration: const Duration(milliseconds: 200),
curve: Curves.ease,
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Private"),
BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
return Switch(
value: state.userData.private,
onChanged: (val) {
UserData userData =
bloc.state.userData.copyWith(private: val);
bloc.add(ProfilePrivateEvent(userData));
},
activeColor: Colors.white,
activeTrackColor: Colors.white.withOpacity(0.3),
inactiveTrackColor: Colors.white.withOpacity(0.3),
);
},
),
],
),
SizedBox(
height: height * 0.01,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InstaText(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.normal,
text: bloc.state.userData.username),
InstaButton(
borderWidth: 0.5,
onPressed: () {
const InstaSnackbar(text: 'Logging out, Please wait!!!')
.show(context);
bloc.add(LogoutEvent());
},
text: "Logout",
fontSize: 16,
textColor: Colors.white,
fontWeight: FontWeight.w700,
buttonColor: Colors.black,
height: height * 0.06,
postButton: true,
width: width * 0.2),
],
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return PageView(
physics: const NeverScrollableScrollPhysics(),
controller: context.read<ProfileBloc>().pageController,
children: [
BlocConsumer<ProfileBloc, ProfileState>(
listener: (context, state) {
if (state is LogoutDoneState) {
Navigator.pop(context);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => BlocProvider(
create: (context) => AuthBloc(),
child: const LoginPage(),
)));
} else if (state is ProfilePrivateState) {
if (state.userData.private) {
Navigator.of(context).pop();
const InstaSnackbar(text: "Your profile is now Private!!!")
.show(context);
} else {
Navigator.of(context).pop();
const InstaSnackbar(text: "Your profile is now Public!!!")
.show(context);
}
}
},
builder: (context, state) {
if (state is UserDataFetched ||
state is UserDataEdited ||
state is ProfilePhotoEdited ||
state is ProfilePrivateState ||
state is TabChangedState ||
state is PostIndexChangedState ||
state is PostLikedProfileState ||
state is CommentAddedProfileState ||
state is DeletedCommentProfileState ||
state is BookmarkedProfileState ||
state is SavedPostsState ||
state is DeletedPostState ||
state is FetchedPreviousStories ||
state is AddingHighLight ||
state is HighLightAddedState ||
state is HighlightDeleted) {
return Scaffold(
backgroundColor: textFieldBackgroundColor,
appBar: AppBar(
elevation: 0,
backgroundColor: textFieldBackgroundColor,
title: SizedBox(
height: AppBar().preferredSize.height,
width: width,
child: Align(
alignment: Alignment.centerLeft,
child: InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.userData.username,
),
),
),
actions: [
IconButton(
onPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor: textFieldBackgroundColor,
context: context,
builder: (_) => BlocProvider.value(
value: context.read<ProfileBloc>(),
child: buildModelBottomSheet(
context,
height,
width,
),
),
);
},
icon: SizedBox(
height: AppBar().preferredSize.height * 0.7,
width: width * 0.065,
child: Image.asset('assets/images/menu_insta.png'),
),
),
],
),
body: Column(
children: [
Padding(
padding: EdgeInsets.only(
top: height * 0.01, left: 12.0, right: 12.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ProfilePhoto(
height: height * 0.13,
width: height * 0.13,
wantBorder: true,
storyAdder: false,
imageUrl: state.userData.profilePhotoUrl,
),
SizedBox(
width: width * 0.1,
),
Row(
children: [
Column(
children: [
InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.userData.posts.length
.toString(),
),
const InstaText(
fontSize: 13,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Posts"),
],
),
SizedBox(
width: width * 0.05,
),
Column(
children: [
InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.userData.followers.length
.toString()),
const InstaText(
fontSize: 13,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Followers")
],
),
SizedBox(
width: width * 0.05,
),
Column(
children: [
InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.userData.following.length
.toString()),
const InstaText(
fontSize: 13,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Following")
],
),
],
),
],
),
SizedBox(
height: height * 0.01,
),
Align(
alignment: Alignment.centerLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.userData.name),
SizedBox(
height: height * 0.003,
),
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.normal,
text: state.userData.bio),
SizedBox(
height: height * 0.003,
),
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.normal,
text: state.userData.tagline),
],
),
),
SizedBox(
height: height * 0.01,
),
InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.05,
buttonColor: Colors.black,
onPressed: () async {
var result = await Navigator.of(context)
.push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value:
context.read<ProfileBloc>(),
child: const EditProfile(),
)));
if (mounted) {
context
.read<HomepageBloc>()
.add(RefreshUi(result));
}
},
text: "Edit Profile",
fontSize: 13,
textColor: Colors.white,
fontWeight: FontWeight.w700),
SizedBox(
height: height * 0.01,
),
Row(
children: [
GestureDetector(
onTap: () {
context
.read<ProfileBloc>()
.add(FetchPreviousStories());
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<ProfileBloc>(),
child: const PreviousStories(),
)));
},
child: Column(
children: [
ProfilePhoto(
height: height * 0.09,
width: height * 0.09,
wantBorder: true,
storyAdder: true,
imageUrl: "",
),
const InstaText(
fontSize: 10,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "New")
],
),
),
SizedBox(
height: height * 0.11,
width: width * 0.7,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: state.userData.stories.length,
itemBuilder: (context, index) {
return Padding(
padding:
const EdgeInsets.only(left: 10.5),
child: GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) =>
MultiBlocProvider(
providers: [
BlocProvider.value(
value: context.read<
HomepageBloc>()),
BlocProvider.value(
value: context.read<
ProfileBloc>()),
BlocProvider(
create: (context) =>
StoryBloc()),
BlocProvider(
create: (context) =>
s.SearchBloc(
PageController(),
FocusNode(),
TextEditingController()))
],
child: ViewStoryPage(
story: state.userData
.stories[index],
inProfile: true,
index: index,
inSearchProfile:
false,
),
)));
},
child: Column(
children: [
ProfilePhoto(
height: height * 0.09,
width: height * 0.09,
wantBorder: true,
storyAdder: false,
imageUrl: state.userData
.stories[index].imageUrl,
),
InstaText(
fontSize: 10,
color: Colors.white,
fontWeight: FontWeight.normal,
text: state.userData
.stories[index].caption,
)
],
),
),
);
},
),
),
],
),
SizedBox(
height: height * 0.01,
),
],
),
),
Column(
children: [
Divider(
color: profilePhotoBorder,
thickness: 0.5,
),
],
),
SizedBox(
height: height * 0.05,
width: double.infinity,
child: TabBar(
onTap: (tabIndex) {
context
.read<ProfileBloc>()
.add(TabChangeEvent(tabIndex));
},
indicatorWeight: 1,
indicatorColor: Colors.white,
controller: tabController,
tabs: [
Tab(
icon: SizedBox(
height: height * 0.03,
child: state.tabIndex == 0
? Image.asset(
'assets/images/selected_grid_icon.png')
: Image.asset(
'assets/images/unselected_grid_icon.png'),
),
),
Tab(
icon: SizedBox(
height: height * 0.03,
child: state.tabIndex == 1
? Image.asset(
'assets/images/selected_tag_icon.png')
: Image.asset('assets/images/tag_icon.png'),
),
)
]),
),
Expanded(
child: TabBarView(
physics: const NeverScrollableScrollPhysics(),
controller: tabController,
children: [
state.userData.posts.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: height * 0.11,
width: height * 0.11,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white, width: 2),
),
child: Center(
child: Image.asset(
"assets/images/insta_camera.png",
scale: 2.5,
),
),
),
SizedBox(
height: height * 0.01,
),
const InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "No Posts Yet")
],
),
)
: GridView.builder(
itemCount: state.userData.posts.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0),
itemBuilder: ((context, index) {
return InkWell(
onTap: () async {
var bloc = context.read<ProfileBloc>();
bloc.add(PostsIndexChangeEvent(index));
await bloc.pageController.animateToPage(
1,
duration:
const Duration(milliseconds: 200),
curve: Curves.ease,
);
},
child: CachedNetworkImage(
imageUrl: state
.userData.posts[index].imageUrl,
fit: BoxFit.fill,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
);
}),
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: height * 0.11,
width: height * 0.11,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white, width: 2)),
child: Center(
child: Image.asset(
"assets/images/selected_tag_icon.png",
scale: 2.5,
),
),
),
SizedBox(
height: height * 0.01,
),
const InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "No Posts Yet")
],
),
),
],
),
),
],
),
);
} else {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
}
},
),
BlocProvider.value(
value: context.read<ProfileBloc>(),
child: const UserPosts(
inProfile: true,
inFeed: false,
),
),
],
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/edit_profile.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/constants/colors.dart';
import 'package:instagram_clone/data/user_data.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/widgets/insta_snackbar.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/profile_widget.dart';
class EditProfile extends StatefulWidget {
const EditProfile({super.key});
@override
State<EditProfile> createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
final TextEditingController nameController = TextEditingController();
final TextEditingController usernameController = TextEditingController();
final TextEditingController bioController = TextEditingController();
final TextEditingController taglineController = TextEditingController();
final TextEditingController contactController = TextEditingController();
final TextEditingController genderController = TextEditingController();
@override
void initState() {
super.initState();
nameController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.name;
usernameController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.username;
bioController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.bio;
taglineController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.tagline;
contactController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.contact;
genderController.text =
BlocProvider.of<ProfileBloc>(context).state.userData.gender == 1
? "Male"
: "Female";
}
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return BlocListener<ProfileBloc, ProfileState>(
listener: (context, state) {
if (state is UserDataEdited) {
Navigator.of(context).pop(state.userData.profilePhotoUrl);
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
leadingWidth: width * 0.2,
backgroundColor: Colors.black,
leading: Align(
alignment: Alignment.centerLeft,
child: SizedBox(
child: TextButton(
style: TextButton.styleFrom(foregroundColor: Colors.black),
onPressed: () {
String imageUrl = context
.read<ProfileBloc>()
.state
.userData
.profilePhotoUrl;
Navigator.of(context).pop(imageUrl);
},
child: const InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Cancel"),
),
),
),
centerTitle: true,
title: const InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "Edit Profile"),
actions: [
Align(
alignment: Alignment.centerRight,
child: TextButton(
style: TextButton.styleFrom(foregroundColor: Colors.black),
onPressed: () {
var bloc = context.read<ProfileBloc>();
UserData userData = UserData(
bloc.state.userData.id,
nameController.text,
usernameController.text,
bloc.state.userData.contact,
bloc.state.userData.password,
bloc.state.userData.gender,
bioController.text,
taglineController.text,
bloc.state.userData.posts,
bloc.state.userData.stories,
bloc.state.userData.followers,
bloc.state.userData.following,
bloc.state.userData.profilePhotoUrl,
bloc.state.userData.private,
bloc.state.userData.bookmarks,
bloc.state.userData.addedStory,
bloc.state.userData.fcmToken,
);
const InstaSnackbar(text: "Saving, Please wait !!!")
.show(context);
bloc.add(EditUserDetails(userData));
},
child: InstaText(
fontSize: 16,
color: instablue,
fontWeight: FontWeight.w700,
text: "Done"),
),
)
],
),
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: height * 0.01,
),
BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is ProfilePhotoLoading) {
return Align(
alignment: Alignment.center,
child: ProfileWidget(
url: state.userData.profilePhotoUrl,
height: height * 0.15,
width: height * 0.15,
wantBorder: true,
photoSelected: false,
editProfileImage: true,
loading: true,
),
);
} else if (state is ProfilePhotoEdited) {
return Align(
alignment: Alignment.center,
child: ProfileWidget(
url: state.userData.profilePhotoUrl,
height: height * 0.15,
width: height * 0.15,
wantBorder: true,
photoSelected: true,
editProfileImage: true,
loading: false,
),
);
} else {
return Align(
alignment: Alignment.center,
child: ProfileWidget(
url: state.userData.profilePhotoUrl,
height: height * 0.15,
width: height * 0.15,
wantBorder: true,
photoSelected:
state.userData.profilePhotoUrl.isNotEmpty,
editProfileImage: true,
loading: false,
),
);
}
},
),
TextButton(
style: TextButton.styleFrom(foregroundColor: Colors.black),
onPressed: () {
var bloc = context.read<ProfileBloc>();
bloc.add(ChangeProfilePhotoEvent(bloc.state.userData));
},
child: InstaText(
fontSize: 13,
color: instablue,
fontWeight: FontWeight.w700,
text: "Change Profile Photo"),
),
SizedBox(
height: height * 0.01,
),
Padding(
padding:
EdgeInsets.only(left: width * 0.05, right: width * 0.05),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Name"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: true,
controller: nameController,
hintText: "name",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Username"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: true,
controller: usernameController,
hintText: "username",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Bio"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: true,
controller: bioController,
hintText: "bio",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Tagline"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: true,
controller: taglineController,
hintText: "tagline",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
SizedBox(
height: height * 0.03,
),
const Align(
alignment: Alignment.centerLeft,
child: InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "Private Information"),
),
SizedBox(
height: height * 0.02,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Contact"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: false,
controller: contactController,
hintText: "contact",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const InstaText(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Gender"),
SizedBox(
width: width * 0.65,
child: InstaTextField(
enabled: false,
controller: genderController,
hintText: "gender",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
icon: null,
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: true,
onChange: (value) {},
),
)
],
),
],
),
)
],
),
),
),
);
}
@override
void dispose() {
nameController.dispose();
bioController.dispose();
taglineController.dispose();
usernameController.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/previous_stories.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/constants/colors.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart';
import 'package:instagram_clone/widgets/instatext.dart';
class PreviousStories extends StatelessWidget {
const PreviousStories({super.key});
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return BlocListener<ProfileBloc, ProfileState>(
listener: (context, state) {
if (state is HighLightAddedState) {
Navigator.of(context).pop();
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
title: const InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "New highlight"),
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(Icons.arrow_back_ios),
),
),
body: BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
if (state is FetchedPreviousStories) {
if (state.previousStories.isEmpty) {
return const Center(
child: InstaText(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "No Stories Yet"),
);
} else {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0),
itemCount: state.previousStories.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () async {
context
.read<ProfileBloc>()
.add(AddHighlight(state.previousStories[index]));
},
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: CachedNetworkImage(
imageUrl: state.previousStories[index].imageUrl,
fit: BoxFit.fill,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
),
);
},
);
}
} else if (state is AddingHighLight) {
return Center(
child: Container(
height: height * 0.15,
width: width * 0.7,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: textFieldBackgroundColor),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
SizedBox(
width: width * 0.05,
),
const InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w500,
text: "Adding Highlight")
],
)),
),
);
} else {
return const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
);
}
},
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/bloc/profile_state.dart | part of 'profile_bloc.dart';
abstract class ProfileState extends Equatable {
final UserData userData;
final int tabIndex;
final int postsIndex;
final bool savedPosts;
final List<Post> savedPostsList;
final List<Story> previousStories;
const ProfileState(this.userData, this.tabIndex, this.postsIndex,
this.savedPosts, this.savedPostsList, this.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class ProfileLoading extends ProfileState {
const ProfileLoading(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class UserDataFetched extends ProfileState {
const UserDataFetched(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class UserDataEdited extends ProfileState {
const UserDataEdited(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class ProfilePhotoEdited extends ProfileState {
const ProfilePhotoEdited(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class ProfilePhotoLoading extends ProfileState {
const ProfilePhotoLoading(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class LogoutDoneState extends ProfileState {
const LogoutDoneState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class ProfilePrivateState extends ProfileState {
const ProfilePrivateState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class TabChangedState extends ProfileState {
const TabChangedState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class PostIndexChangedState extends ProfileState {
const PostIndexChangedState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class PostLikedProfileState extends ProfileState {
const PostLikedProfileState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class CommentAddedProfileState extends ProfileState {
const CommentAddedProfileState(
super.userData,
super.tabIndex,
super.postsIndex,
super.savedPosts,
super.savedPostsList,
super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class DeletedCommentProfileState extends ProfileState {
const DeletedCommentProfileState(
super.userData,
super.tabIndex,
super.postsIndex,
super.savedPosts,
super.savedPostsList,
super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class BookmarkedProfileState extends ProfileState {
const BookmarkedProfileState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class SavedPostsState extends ProfileState {
const SavedPostsState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class DeletedPostState extends ProfileState {
const DeletedPostState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class FetchedPreviousStories extends ProfileState {
const FetchedPreviousStories(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class HighLightAddedState extends ProfileState {
const HighLightAddedState(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class AddingHighLight extends ProfileState {
const AddingHighLight(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class DeletingHighLight extends ProfileState {
const DeletingHighLight(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
class HighlightDeleted extends ProfileState {
const HighlightDeleted(super.userData, super.tabIndex, super.postsIndex,
super.savedPosts, super.savedPostsList, super.previousStories);
@override
List<Object> get props => [
userData,
tabIndex,
postsIndex,
savedPosts,
savedPostsList,
previousStories
];
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.