repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/bloc/profile_bloc.dart | import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_clone/data/comment_data.dart';
import 'package:instagram_clone/data/posts_data.dart';
import 'package:instagram_clone/data/stories.dart';
import 'package:instagram_clone/data/user_data.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:uuid/uuid.dart';
part 'profile_event.dart';
part 'profile_state.dart';
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
ProfileBloc(this.pageController)
: super(
ProfileLoading(UserData.temp(), 0, 0, false, const [], const [])) {
on<GetUserDetails>((event, emit) => getUserDetails(event, emit));
on<EditUserDetails>((event, emit) => editUserDetails(event, emit));
on<ChangeProfilePhotoEvent>(
(event, emit) => changeProfilePhotoEvent(event, emit));
on<LogoutEvent>((event, emit) => logout(event, emit));
on<ProfilePrivateEvent>((event, emit) => changeProfileStatus(event, emit));
on<TabChangeEvent>((event, emit) => emit(TabChangedState(
state.userData,
event.tabIndex,
state.postsIndex,
state.savedPosts,
state.savedPostsList, const [])));
on<PostsIndexChangeEvent>((event, emit) => emit(PostIndexChangedState(
state.userData,
state.tabIndex,
event.postIndex,
false,
state.savedPostsList, const [])));
on<LikePostEvent>((event, emit) => likePost(event, emit));
on<AddProfileComment>((event, emit) => addComment(event, emit));
on<DeleteProfileComment>((event, emit) => deleteComment(event, emit));
on<BookmarkProfile>((event, emit) => addBookmark(event, emit));
on<ShowSavedPosts>((event, emit) => getSavedPosts(event, emit));
on<DeletePost>((event, emit) => deletePost(event, emit));
on<FetchPreviousStories>((event, emit) => fetchStories(event, emit));
on<AddHighlight>((event, emit) => addHighlight(event, emit));
on<DeleteHighlight>((event, emit) => deleteHighlight(event, emit));
on<ShareProfileFileEvent>((event, emit) => shareFile(event, emit));
}
final PageController pageController;
Future<void> shareFile(ShareProfileFileEvent event, Emitter emit) async {
var response = await Dio().get(event.imageUrl,
options: Options(responseType: ResponseType.bytes));
Directory dir = await getTemporaryDirectory();
File file = File('${dir.path}/image.png');
await file.writeAsBytes(response.data);
await Share.shareXFiles([XFile(file.path)], text: event.caption);
}
Future<void> deleteHighlight(DeleteHighlight event, Emitter emit) async {
emit(DeletingHighLight(state.userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, state.previousStories));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
List<Story> highlights = state.userData.stories;
highlights.removeAt(event.index);
UserData userData = state.userData.copyWith(stories: highlights);
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(HighlightDeleted(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, state.previousStories));
}
Future<void> addHighlight(AddHighlight event, Emitter emit) async {
emit(AddingHighLight(state.userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, state.previousStories));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
List<Story> highlights = state.userData.stories;
highlights.add(event.story);
UserData userData = state.userData.copyWith(stories: highlights);
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(HighLightAddedState(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, state.previousStories));
}
Future<void> fetchStories(FetchPreviousStories event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
var docSnapshot = await FirebaseFirestore.instance
.collection("stories")
.doc(userId)
.get();
var docData = docSnapshot.data()!;
List<Story> previousStories = [];
for (var story in docData['previous_stories']) {
previousStories.add(Story.fromJson(story));
}
emit(FetchedPreviousStories(
state.userData,
state.tabIndex,
state.postsIndex,
state.savedPosts,
state.savedPostsList,
previousStories));
}
Future<void> deletePost(DeletePost event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
List<Post> posts = List.from(state.userData.posts);
posts.removeAt(event.index);
UserData userData = state.userData.copyWith(posts: posts);
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(DeletedPostState(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
Future<void> getSavedPosts(ShowSavedPosts event, Emitter emit) async {
emit(ProfileLoading(state.userData, state.tabIndex, state.postsIndex, true,
state.savedPostsList, const []));
var firestoreCollectionRef = FirebaseFirestore.instance.collection("users");
List bookmarkedPostsList = state.userData.bookmarks;
List<Post> savedPostsList = [];
var snapshot = await firestoreCollectionRef.get();
var docsList = snapshot.docs;
for (int i = 0; i < docsList.length; i++) {
UserData userData = UserData.fromJson(docsList[i].data());
List<Post> posts = userData.posts;
for (int j = 0; j < posts.length; j++) {
if (bookmarkedPostsList.contains(posts[j].id)) {
savedPostsList.add(posts[j]);
}
}
}
savedPostsList.shuffle();
emit(SavedPostsState(state.userData, state.tabIndex, state.postsIndex, true,
savedPostsList, const []));
}
Future<void> addBookmark(BookmarkProfile event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String myUserId = sharedPreferences.getString("userId")!;
List bookmarks = List.from(state.userData.bookmarks);
String postId = state.savedPosts
? state.savedPostsList[event.postIndex].id
: state.userData.posts[event.postIndex].id;
List<Post> savedPostsList = [];
if (bookmarks.contains(postId)) {
bookmarks.remove(postId);
if (state.savedPosts) {
savedPostsList = state.savedPostsList;
savedPostsList.removeAt(event.postIndex);
}
} else {
bookmarks.add(postId);
}
UserData userData = state.userData.copyWith(bookmarks: bookmarks);
await FirebaseFirestore.instance
.collection("users")
.doc(myUserId)
.update(userData.toJson());
emit(BookmarkedProfileState(
userData,
state.tabIndex,
state.postsIndex,
state.savedPosts,
state.savedPosts ? savedPostsList : state.savedPostsList, const []));
}
Future<void> addComment(AddProfileComment event, Emitter emit) async {
List<Comments> existingcomments = List.from(event.comments);
String userId = state.userData.id;
String profilePhotoUrl = state.userData.profilePhotoUrl;
String username = state.userData.username;
String id = const Uuid().v4();
Comments newComment =
Comments(event.comment, profilePhotoUrl, username, userId, id);
existingcomments.add(newComment);
if (state.savedPosts) {
List<Post> posts = List.from(state.savedPostsList);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingcomments);
String userId = posts[event.postIndex].userId;
var firestoreCollectionRef =
FirebaseFirestore.instance.collection("users");
var docSnapshot = await firestoreCollectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List<Post> userPosts = userData.posts;
for (int i = 0; i < userPosts.length; i++) {
if (userPosts[i].id == posts[event.postIndex].id) {
userPosts[i] = userPosts[i].copyWith(comments: existingcomments);
}
}
UserData data = userData.copyWith(posts: userPosts);
await firestoreCollectionRef.doc(userId).update(data.toJson());
emit(CommentAddedProfileState(state.userData, state.tabIndex,
state.postsIndex, state.savedPosts, posts, const []));
} else {
List<Post> posts = List.from(state.userData.posts);
posts[event.postIndex] = state.userData.posts[event.postIndex]
.copyWith(comments: existingcomments);
UserData userData = state.userData.copyWith(posts: posts);
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(CommentAddedProfileState(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
}
Future<void> deleteComment(DeleteProfileComment event, Emitter emit) async {
List<Comments> exisitingComments = state.savedPosts
? List.from(state.savedPostsList[event.postIndex].comments)
: List.from(state.userData.posts[event.postIndex].comments);
exisitingComments.removeAt(event.commentIndex);
if (state.savedPosts) {
List<Post> savedPostsList = List.from(state.savedPostsList);
savedPostsList[event.postIndex] =
savedPostsList[event.postIndex].copyWith(comments: exisitingComments);
String userId = savedPostsList[event.postIndex].userId;
var firestoreCollectionRef =
FirebaseFirestore.instance.collection("users");
var docSnapshot = await firestoreCollectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List<Post> posts = userData.posts;
for (int i = 0; i < posts.length; i++) {
if (posts[i].id == savedPostsList[event.postIndex].id) {
posts[i] = posts[i].copyWith(comments: exisitingComments);
}
}
UserData updatedUserData = userData.copyWith(posts: posts);
await firestoreCollectionRef.doc(userId).update(updatedUserData.toJson());
emit(DeletedCommentProfileState(state.userData, state.tabIndex,
state.postsIndex, state.savedPosts, savedPostsList, const []));
} else {
List<Post> posts = state.userData.posts;
posts[event.postIndex] = state.userData.posts[event.postIndex]
.copyWith(comments: exisitingComments);
UserData userData = state.userData.copyWith(posts: posts);
String userId = state.userData.id;
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(DeletedCommentProfileState(userData, state.tabIndex,
state.postsIndex, state.savedPosts, state.savedPostsList, const []));
}
}
Future<void> likePost(LikePostEvent event, Emitter emit) async {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final collectionRef = firebaseFirestore.collection("users");
if (state.savedPosts) {
List<Post> savedPostsList = List.from(state.savedPostsList);
List likes = savedPostsList[event.index].likes;
if (likes.contains(myUserId)) {
likes.remove(myUserId);
} else {
likes.add(myUserId);
}
savedPostsList[event.index] =
savedPostsList[event.index].copyWith(likes: likes);
String userId = savedPostsList[event.index].userId;
var docSnapshot = await collectionRef.doc(userId).get();
var docData = docSnapshot.data()!;
UserData userData = UserData.fromJson(docData);
List<Post> posts = userData.posts;
for (int i = 0; i < posts.length; i++) {
if (savedPostsList[event.index].id == posts[i].id) {
posts[i].likes = likes;
}
}
UserData updatedUserData = userData.copyWith(posts: posts);
await collectionRef.doc(userId).update(updatedUserData.toJson());
emit(PostLikedProfileState(state.userData, state.tabIndex,
state.postsIndex, state.savedPosts, savedPostsList, const []));
} else {
var documentData = collectionRef.doc(myUserId);
List<Post> posts = List.from(state.userData.posts);
List likes = posts[event.index].likes;
if (likes.contains(myUserId)) {
likes.remove(myUserId);
} else {
likes.add(myUserId);
}
posts[event.index] =
state.userData.posts[event.index].copyWith(likes: likes);
UserData userData = state.userData.copyWith(posts: posts);
var value = await documentData.get();
var data = value.data()!;
data["posts"][event.index]["likes"] = likes;
await documentData.update(data);
emit(PostLikedProfileState(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
}
Future<void> changeProfileStatus(
ProfilePrivateEvent event, Emitter emit) async {
var firestoreCollectionRef = FirebaseFirestore.instance.collection('users');
await firestoreCollectionRef
.doc(event.userData.id)
.update({"private": event.userData.private});
emit(ProfilePrivateState(event.userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
Future<void> logout(LogoutEvent event, Emitter emit) async {
var sharedPrefernces = await SharedPreferences.getInstance();
await sharedPrefernces.clear();
emit(LogoutDoneState(state.userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
Future<void> getUserDetails(GetUserDetails event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
var userId = sharedPreferences.getString("userId");
var collectionRef = FirebaseFirestore.instance.collection("users");
Query<Map<String, dynamic>> queriedData =
collectionRef.where("id", isEqualTo: userId);
var snapshotData = await queriedData.get();
UserData userData = UserData.fromJson(snapshotData.docs.first.data());
if (kDebugMode) {
print(userData);
}
emit(UserDataFetched(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
Future<void> editUserDetails(EditUserDetails event, Emitter emit) async {
var collectionRef = FirebaseFirestore.instance.collection("users");
await collectionRef.doc(event.userData.id).update({
"name": event.userData.name,
"username": event.userData.username,
"tagline": event.userData.tagline,
"bio": event.userData.bio,
"profilePhotoUrl": event.userData.profilePhotoUrl,
});
emit(UserDataEdited(event.userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
Future<void> changeProfilePhotoEvent(
ChangeProfilePhotoEvent event, Emitter emit) async {
emit(ProfilePhotoLoading(event.userData.copyWith(), state.tabIndex,
state.postsIndex, state.savedPosts, state.savedPostsList, const []));
var profileImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
var storageRef = FirebaseStorage.instance.ref();
Reference imagesRef = storageRef.child(event.userData.id);
const fileName = "profilePhoto.jpg";
final profilePhotoRef = imagesRef.child(fileName);
// final path = profilePhotoRef.fullPath;
File image = File(profileImage!.path);
await profilePhotoRef.putFile(image);
final imagePath = await profilePhotoRef.getDownloadURL();
await FirebaseFirestore.instance
.collection("users")
.doc(event.userData.id)
.update({"profilePhotoUrl": imagePath});
UserData userData = event.userData.copyWith(profilePhotoUrl: imagePath);
emit(ProfilePhotoEdited(userData, state.tabIndex, state.postsIndex,
state.savedPosts, state.savedPostsList, const []));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/profile/bloc/profile_event.dart | part of 'profile_bloc.dart';
abstract class ProfileEvent extends Equatable {
const ProfileEvent();
@override
List<Object> get props => [];
}
class GetUserDetails extends ProfileEvent {}
class EditUserDetails extends ProfileEvent {
final UserData userData;
const EditUserDetails(this.userData);
@override
List<Object> get props => [userData];
}
class ChangeProfilePhotoEvent extends ProfileEvent {
final UserData userData;
const ChangeProfilePhotoEvent(this.userData);
@override
List<Object> get props => [userData];
}
class LogoutEvent extends ProfileEvent {}
class ProfilePrivateEvent extends ProfileEvent {
final UserData userData;
const ProfilePrivateEvent(this.userData);
@override
List<Object> get props => [userData];
}
class TabChangeEvent extends ProfileEvent {
final int tabIndex;
const TabChangeEvent(this.tabIndex);
@override
List<Object> get props => [tabIndex];
}
class PostsIndexChangeEvent extends ProfileEvent {
final int postIndex;
const PostsIndexChangeEvent(this.postIndex);
@override
List<Object> get props => [postIndex];
}
class LikePostEvent extends ProfileEvent {
final int index;
const LikePostEvent(this.index);
@override
List<Object> get props => [index];
}
class AddProfileComment extends ProfileEvent {
final List<Comments> comments;
final int postIndex;
final String comment;
const AddProfileComment(this.comments, this.postIndex, this.comment);
@override
List<Object> get props => [comments, postIndex, comment];
}
class DeleteProfileComment extends ProfileEvent {
final int postIndex;
final int commentIndex;
const DeleteProfileComment(this.postIndex, this.commentIndex);
@override
List<Object> get props => [postIndex, commentIndex];
}
class BookmarkProfile extends ProfileEvent {
final int postIndex;
const BookmarkProfile(this.postIndex);
@override
List<Object> get props => [postIndex];
}
class ShowSavedPosts extends ProfileEvent {}
class DeletePost extends ProfileEvent {
final int index;
const DeletePost(this.index);
@override
List<Object> get props => [index];
}
class FetchPreviousStories extends ProfileEvent {}
class AddHighlight extends ProfileEvent {
final Story story;
const AddHighlight(this.story);
@override
List<Object> get props => [story];
}
class DeleteHighlight extends ProfileEvent {
final int index;
const DeleteHighlight(this.index);
@override
List<Object> get props => [index];
}
class ShareProfileFileEvent extends ProfileEvent {
final String imageUrl;
final String caption;
const ShareProfileFileEvent({required this.imageUrl, required this.caption});
@override
List<Object> get props => [imageUrl, caption];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/comment_page.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/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/comment_list.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
class CommentPage extends StatefulWidget {
const CommentPage({
super.key,
required this.searchState,
required this.feedState,
required this.profileState,
required this.postIndex,
required this.sharedPreferences,
required this.inFeed,
});
final SearchState? searchState;
final FeedState? feedState;
final ProfileState? profileState;
final int postIndex;
final SharedPreferences sharedPreferences;
final bool inFeed;
@override
State<CommentPage> createState() => _CommentPageState();
}
class _CommentPageState extends State<CommentPage> {
final TextEditingController controller = 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(
backgroundColor: Colors.black,
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "Comments",
),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
child: widget.searchState != null
? BlocBuilder<SearchBloc, SearchState>(
builder: (context, state) {
List<Comments> comments = [];
if (state.usersPosts) {
comments.add(
Comments(
state.userData.posts[widget.postIndex].caption,
state.userData.posts[widget.postIndex]
.userProfilePhotoUrl,
state.userData.posts[widget.postIndex].username,
state.userData.posts[widget.postIndex].userId,
state.userData.posts[widget.postIndex].id,
),
);
comments.addAll(
state.userData.posts[widget.postIndex].comments);
} else {
comments.add(
Comments(
state.posts[widget.postIndex].caption,
state.posts[widget.postIndex].userProfilePhotoUrl,
state.posts[widget.postIndex].username,
state.posts[widget.postIndex].userId,
state.posts[widget.postIndex].id,
),
);
comments
.addAll(state.posts[widget.postIndex].comments);
}
return CommentList(
postIndex: widget.postIndex,
width: width,
comments: comments,
tileHeight: height * 0.08,
height: height,
sharedPreferences: widget.sharedPreferences,
searchComments: true,
feedComments: false,
profileComments: false,
inFeed: false,
);
},
)
: widget.profileState != null
? BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
List<Comments> comments = [];
comments.add(
Comments(
state.savedPosts
? state.savedPostsList[widget.postIndex]
.caption
: state.userData.posts[widget.postIndex]
.caption,
state.savedPosts
? state.savedPostsList[widget.postIndex]
.userProfilePhotoUrl
: state.userData.posts[widget.postIndex]
.userProfilePhotoUrl,
state.savedPosts
? state.savedPostsList[widget.postIndex]
.username
: state.userData.posts[widget.postIndex]
.username,
state.savedPosts
? state
.savedPostsList[widget.postIndex].userId
: state.userData.posts[widget.postIndex]
.userId,
state.savedPosts
? state.savedPostsList[widget.postIndex].id
: state.userData.posts[widget.postIndex].id,
),
);
comments.addAll(state.savedPosts
? state
.savedPostsList[widget.postIndex].comments
: state
.userData.posts[widget.postIndex].comments);
return CommentList(
postIndex: widget.postIndex,
width: width,
comments: comments,
tileHeight: height * 0.08,
height: height,
sharedPreferences: widget.sharedPreferences,
profileComments: true,
feedComments: false,
searchComments: false,
inFeed: false,
);
},
)
: widget.feedState != null
? BlocBuilder<FeedBloc, FeedState>(
builder: (context, state) {
List<Comments> comments = [];
String id = const Uuid().v4();
if (widget.inFeed) {
comments.add(
Comments(
state.posts[widget.postIndex].caption,
state.posts[widget.postIndex]
.userProfilePhotoUrl,
state.posts[widget.postIndex].username,
state.posts[widget.postIndex].userId,
id,
),
);
comments.addAll(
state.posts[widget.postIndex].comments);
} else {
comments.add(
Comments(
state.userData.posts[widget.postIndex]
.caption,
state.userData.posts[widget.postIndex]
.userProfilePhotoUrl,
state.userData.posts[widget.postIndex]
.username,
state.userData.posts[widget.postIndex]
.userId,
id,
),
);
comments.addAll(state.userData
.posts[widget.postIndex].comments);
}
return CommentList(
postIndex: widget.postIndex,
sharedPreferences: widget.sharedPreferences,
width: width,
comments: comments,
tileHeight: height * 0.08,
height: height,
feedComments: true,
inFeed: widget.inFeed,
searchComments: false,
profileComments: false,
);
},
)
: CommentList(
postIndex: widget.postIndex,
width: width,
comments: const [],
tileHeight: height * 0.08,
height: height,
sharedPreferences: widget.sharedPreferences,
feedComments: true,
inFeed: true,
profileComments: false,
searchComments: false,
),
),
Row(
children: [
Expanded(
child: InstaTextField(
controller: controller,
hintText: "comment",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.5),
obscureText: false,
icon: const Icon(
Icons.comment,
color: Colors.white,
),
borderRadius: 0,
backgroundColor: Colors.black,
forPassword: false,
suffixIconCallback: () {},
editProfileTextfield: false,
enabled: true,
onChange: (value) {})),
GestureDetector(
onTap: () {
if (widget.searchState != null) {
var bloc = context.read<SearchBloc>();
List<Comments> comments = bloc.state.usersPosts
? bloc.state.userData.posts[widget.postIndex].comments
: bloc.state.posts[widget.postIndex].comments;
bloc.add(AddSearchComment(
comments, widget.postIndex, controller.text));
} else if (widget.profileState != null) {
var bloc = context.read<ProfileBloc>();
List<Comments> comments = bloc.state.savedPosts
? bloc.state.savedPostsList[widget.postIndex].comments
: bloc
.state.userData.posts[widget.postIndex].comments;
bloc.add(AddProfileComment(
comments, widget.postIndex, controller.text));
} else if (widget.feedState != null) {
var bloc = context.read<FeedBloc>();
List<Comments> comments = widget.inFeed
? bloc.state.posts[widget.postIndex].comments
: bloc
.state.userData.posts[widget.postIndex].comments;
if (widget.inFeed) {
bloc.add(AddFeedComment(comments, widget.postIndex,
controller.text, widget.inFeed));
} else {
bloc.add(AddFeedComment(comments, widget.postIndex,
controller.text, widget.inFeed));
}
}
controller.clear();
FocusManager.instance.primaryFocus!.unfocus();
},
child: SizedBox(
width: width * 0.15,
child: Align(
alignment: Alignment.center,
child: InstaText(
fontSize: 16,
color: instablue,
fontWeight: FontWeight.w700,
text: "Post"),
),
),
),
],
)
],
),
),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/feed.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/constants/colors.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/comment_page.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/story/add_story.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/search/bloc/search_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/user_profile.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/post_tile.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
import 'package:instagram_clone/widgets/user_posts.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'bloc/feed_bloc.dart';
class FeedPage extends StatelessWidget {
const FeedPage({super.key});
Widget buildBottomSheet(
BuildContext context, double height, double width, int index) {
var feedState = context.read<FeedBloc>().state;
return SizedBox(
height: height * 0.3,
child: Padding(
padding: const EdgeInsets.only(
top: 16.0,
bottom: 16.0,
),
child: Column(
children: [
GestureDetector(
onTap: () {
context.read<FeedBloc>().add(BookmarkFeed(index, true));
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.myData.bookmarks
.contains(feedState.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),
),
ListTile(
minLeadingWidth: 0,
leading: feedState.myData.following
.contains(feedState.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: feedState.myData.following
.contains(feedState.posts[index].userId)
? "Unfollow"
: "follow",
),
onTap: () {
if (feedState.myData.following
.contains(feedState.posts[index].userId)) {
context
.read<FeedBloc>()
.add(UnFollowFeedEvent(fromFeed: true, index: index));
} else {
context
.read<FeedBloc>()
.add(FollowFeedEvent(fromFeed: true, index: index));
}
Navigator.of(context).pop();
},
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
return PageView(
physics: const NeverScrollableScrollPhysics(),
controller: context.read<FeedBloc>().pageController,
children: [
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'),
),
// actions: [
// IconButton(
// onPressed: () {},
// icon: SizedBox(
// height: AppBar().preferredSize.height * 0.8,
// width: width * 0.07,
// child: Image.asset('assets/images/messanger.png'),
// ),
// ),
// ],
),
body: BlocBuilder<FeedBloc, FeedState>(
builder: (context, state) {
if (state is FeedFetched ||
state is PostLikedState ||
state is CommentAddedState ||
state is CommentDeletedState ||
state is BookmarkedState ||
state is UserDataLoadingState ||
state is UserDataFetchedState ||
state is TabChangedFeedState ||
state is PostIndexChangeFeedState ||
state is MyStoryFetchedState ||
state is MyStoryDeletedState ||
state is FollowingFeedState ||
state is FollowedUserFeedState ||
state is UnFollowedUserFeedState ||
state is UnFollowingFeedState ||
state is StoryViewedState) {
return ListView.builder(
itemCount: state.posts.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
padding: const EdgeInsets.only(top: 2),
child: Row(
children: [
SizedBox(
height: height * 0.11,
width: width * 0.2,
child: GestureDetector(
onTap: () {
if (state.myData.addedStory) {
context.read<FeedBloc>().add(
const StoryViewEvent(
viewMyStory: true));
Navigator.of(context)
.push(MaterialPageRoute(
builder: (_) => MultiBlocProvider(
providers: [
BlocProvider.value(
value: context.read<
HomepageBloc>()),
BlocProvider(
create: (context) =>
StoryBloc(),
),
BlocProvider.value(
value: context
.read<FeedBloc>(),
),
BlocProvider(
create: (context) =>
ProfileBloc(
PageController())),
BlocProvider(
create: (context) =>
SearchBloc(
PageController(),
FocusNode(),
TextEditingController()))
],
child: ViewStoryPage(
story:
state.myStory.story,
inProfile: false,
index: index,
inSearchProfile: false,
),
)));
} else {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => MultiBlocProvider(
providers: [
BlocProvider(
create: (context) =>
StoryBloc()),
BlocProvider.value(
value: context
.read<FeedBloc>(),
)
],
child:
const AddStoryPage())));
}
},
child: Column(
children: [
Stack(
alignment: Alignment.center,
children: [
ProfilePhoto(
height: height * 0.09,
width: height * 0.09,
wantBorder: false,
storyAdder: false,
imageUrl:
state.myData.profilePhotoUrl,
),
state.myData.addedStory
? state.myStory.viewed
? Container()
: Container(
height: height * 0.09,
width: height * 0.09,
decoration:
BoxDecoration(
shape:
BoxShape.circle,
border: Border.all(
width: 2,
color: Colors
.pink.shade900,
),
),
)
: Positioned(
bottom: 8,
right: 8,
child: Container(
height: width * 0.04,
width: width * 0.04,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: instablue,
),
child: const Center(
child: Icon(
Icons.add,
color: Colors.white,
size: 11,
),
),
),
)
]),
const InstaText(
fontSize: 10,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Your story"),
],
),
),
),
SizedBox(
height: height * 0.11,
width: width * 0.8,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: state.stories.length,
itemBuilder: (context, index) {
return Padding(
padding:
const EdgeInsets.only(left: 10.5),
child: GestureDetector(
onTap: () {
context.read<FeedBloc>().add(
StoryViewEvent(
viewMyStory: false,
index: index));
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) =>
MultiBlocProvider(
providers: [
BlocProvider.value(
value: context.read<
HomepageBloc>()),
BlocProvider(
create: (context) =>
StoryBloc(),
),
BlocProvider.value(
value: context.read<
FeedBloc>(),
),
BlocProvider(
create: (context) =>
ProfileBloc(
PageController())),
],
child: ViewStoryPage(
story: state
.stories[index]
.story,
inProfile: false,
index: index,
inSearchProfile:
false,
))));
},
child: Column(
children: [
Stack(
alignment: Alignment.center,
children: [
ProfilePhoto(
height: height * 0.09,
width: height * 0.09,
wantBorder: false,
storyAdder: false,
imageUrl: state
.stories[index]
.story
.userProfilePhotoUrl,
),
state.stories[index].viewed
? Container()
: Container(
height: height * 0.09,
width: height * 0.09,
decoration: BoxDecoration(
shape: BoxShape
.circle,
border: Border.all(
width: 2,
color: Colors
.pink
.shade900)),
)
]),
InstaText(
fontSize: 10,
color: Colors.white,
fontWeight: FontWeight.normal,
text: state.stories[index].story
.username),
],
),
),
);
},
),
),
],
),
);
} else {
return PostTile(
isFeedData: true,
width: width,
height: height,
profileState: null,
searchState: null,
index: index - 1,
feedState: state,
onUserNamePressed: () async {
var bloc = context.read<FeedBloc>();
bloc.add(
FetchUserData(state.posts[index - 1].userId));
await bloc.pageController.animateToPage(1,
duration: const Duration(milliseconds: 200),
curve: Curves.ease);
},
optionPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
backgroundColor: textFieldBackgroundColor,
context: context,
builder: (_) => BlocProvider.value(
value: context.read<FeedBloc>(),
child: buildBottomSheet(
context,
height,
width,
index - 1,
),
));
},
likePressed: () {
context.read<FeedBloc>().add(PostLikeEvent(
state.posts[index - 1].id,
index - 1,
state.posts[index - 1].userId,
true));
},
onDoubleTap: () {
context.read<FeedBloc>().add(PostLikeEvent(
state.posts[index - 1].id,
index - 1,
state.posts[index - 1].userId,
true));
},
commentPressed: () async {
var sharedPreferences =
await SharedPreferences.getInstance();
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<FeedBloc>(),
child: CommentPage(
sharedPreferences: sharedPreferences,
feedState: state,
profileState: null,
searchState: null,
postIndex: index - 1,
inFeed: true,
),
)));
},
bookmarkPressed: () {
context
.read<FeedBloc>()
.add(BookmarkFeed(index - 1, true));
},
sharePressed: () async {
context.read<FeedBloc>().add(ShareFileEvent(
imageUrl: state.posts[index - 1].imageUrl,
caption: state.posts[index - 1].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);
},
);
}
});
} else {
return const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
);
}
},
),
),
BlocProvider.value(
value: context.read<FeedBloc>(),
child: UserProfilePage(
inSearch: false,
pageController: context.read<FeedBloc>().pageController,
),
),
BlocProvider.value(
value: context.read<FeedBloc>(),
child: const UserPosts(
inProfile: false,
inFeed: true,
),
)
],
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/bloc/feed_event.dart | part of 'feed_bloc.dart';
abstract class FeedEvent extends Equatable {
const FeedEvent();
@override
List<Object> get props => [];
}
class GetFeed extends FeedEvent {
final bool atStart;
const GetFeed(this.atStart);
@override
List<Object> get props => [atStart];
}
class PostLikeEvent extends FeedEvent {
final String postId;
final int index;
final String userId;
final bool inFeed;
const PostLikeEvent(this.postId, this.index, this.userId, this.inFeed);
@override
List<Object> get props => [postId, index, userId, inFeed];
}
class AddFeedComment extends FeedEvent {
final List<Comments> comments;
final int postIndex;
final String comment;
final bool inFeed;
const AddFeedComment(
this.comments, this.postIndex, this.comment, this.inFeed);
@override
List<Object> get props => [comments, postIndex, comment, inFeed];
}
class DeleteFeedComment extends FeedEvent {
final int postIndex;
final int commentIndex;
final bool inFeed;
const DeleteFeedComment(this.postIndex, this.commentIndex, this.inFeed);
@override
List<Object> get props => [postIndex, commentIndex, inFeed];
}
class BookmarkFeed extends FeedEvent {
final int postIndex;
final bool inFeed;
const BookmarkFeed(this.postIndex, this.inFeed);
@override
List<Object> get props => [postIndex, inFeed];
}
class FetchUserData extends FeedEvent {
final String userId;
const FetchUserData(this.userId);
@override
List<Object> get props => [userId];
}
class TabChangeFeedEvent extends FeedEvent {
final int tabIndex;
const TabChangeFeedEvent(this.tabIndex);
@override
List<Object> get props => [tabIndex];
}
class FeedPostsIndexChangeEvent extends FeedEvent {
final int postIndex;
const FeedPostsIndexChangeEvent(this.postIndex);
@override
List<Object> get props => [postIndex];
}
class GetMyStory extends FeedEvent {}
class DeleteMyStory extends FeedEvent {}
class FollowFeedEvent extends FeedEvent {
final bool fromFeed;
final int? index;
const FollowFeedEvent({required this.fromFeed, this.index});
@override
List<Object> get props => [fromFeed];
}
class UnFollowFeedEvent extends FeedEvent {
final bool fromFeed;
final int? index;
const UnFollowFeedEvent({required this.fromFeed, this.index});
@override
List<Object> get props => [fromFeed];
}
class StoryViewEvent extends FeedEvent {
final bool viewMyStory;
final int? index;
const StoryViewEvent({required this.viewMyStory, this.index});
@override
List<Object> get props => [viewMyStory];
}
class ShareFileEvent extends FeedEvent {
final String imageUrl;
final String caption;
const ShareFileEvent({required this.caption, required this.imageUrl});
@override
List<Object> get props => [imageUrl];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/bloc/feed_state.dart | part of 'feed_bloc.dart';
abstract class FeedState extends Equatable {
const FeedState(this.posts, this.myData, this.userData, this.tabIndex,
this.postsIndex, this.stories, this.myStory);
final List<Post> posts;
final UserData myData;
final UserData userData;
final int postsIndex;
final int tabIndex;
final List<StoryData> stories;
final StoryData myStory;
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class FeedInitial extends FeedState {
const FeedInitial(super.posts, super.myData, super.userData, super.tabIndex,
super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class FeedFetched extends FeedState {
const FeedFetched(super.posts, super.myData, super.userData, super.tabIndex,
super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class PostLikedState extends FeedState {
const PostLikedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class CommentAddedState extends FeedState {
const CommentAddedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class CommentDeletedState extends FeedState {
const CommentDeletedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class BookmarkedState extends FeedState {
const BookmarkedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class UserDataLoadingState extends FeedState {
const UserDataLoadingState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class UserDataFetchedState extends FeedState {
const UserDataFetchedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class TabChangedFeedState extends FeedState {
const TabChangedFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class PostIndexChangeFeedState extends FeedState {
const PostIndexChangeFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class MyStoryFetchedState extends FeedState {
const MyStoryFetchedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class MyStoryDeletedState extends FeedState {
const MyStoryDeletedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class FollowedUserFeedState extends FeedState {
const FollowedUserFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class FollowingFeedState extends FeedState {
const FollowingFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class UnFollowingFeedState extends FeedState {
const UnFollowingFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class UnFollowedUserFeedState extends FeedState {
const UnFollowedUserFeedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
class StoryViewedState extends FeedState {
const StoryViewedState(super.posts, super.myData, super.userData,
super.tabIndex, super.postsIndex, super.stories, super.myStory);
@override
List<Object> get props =>
[posts, myData, userData, tabIndex, postsIndex, stories, myStory];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart | import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:instagram_clone/data/comment_data.dart';
import 'package:instagram_clone/data/notification_data.dart';
import 'package:instagram_clone/data/posts_data.dart';
import 'package:instagram_clone/data/stories.dart';
import 'package:instagram_clone/data/user_data.dart';
import 'package:instagram_clone/utility/notification_service.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
part 'feed_event.dart';
part 'feed_state.dart';
class FeedBloc extends Bloc<FeedEvent, FeedState> {
final PageController pageController;
FeedBloc(this.pageController)
: super(FeedInitial(const <Post>[], UserData.temp(), UserData.temp(), 0,
0, const [], StoryData(story: Story.temp(), viewed: false))) {
on<GetFeed>((event, emit) => getPosts(event, emit));
on<PostLikeEvent>((event, emit) => likePost(event, emit));
on<AddFeedComment>((event, emit) => addComment(event, emit));
on<DeleteFeedComment>((event, emit) => deleteComment(event, emit));
on<BookmarkFeed>((event, emit) => addBookmark(event, emit));
on<FetchUserData>((event, emit) => fetchUserData(event, emit));
on<TabChangeFeedEvent>((event, emit) => emit(TabChangedFeedState(
state.posts,
state.myData,
state.userData,
event.tabIndex,
state.postsIndex,
state.stories,
state.myStory)));
on<FeedPostsIndexChangeEvent>((event, emit) => emit(
PostIndexChangeFeedState(state.posts, state.myData, state.userData,
state.tabIndex, event.postIndex, state.stories, state.myStory)));
on<GetMyStory>((event, emit) => getMyStory(event, emit));
on<DeleteMyStory>((event, emit) => deleteMyStory(event, emit));
on<FollowFeedEvent>((event, emit) => follow(event, emit));
on<UnFollowFeedEvent>((event, emit) => unfollow(event, emit));
on<StoryViewEvent>((event, emit) => viewStory(event, emit));
on<ShareFileEvent>((event, emit) => shareFile(event, emit));
}
Future<void> shareFile(ShareFileEvent event, Emitter emit) async {
var response = await Dio().get(event.imageUrl,
options: Options(responseType: ResponseType.bytes));
Directory dir = await getTemporaryDirectory();
File file = File('${dir.path}/image.png');
await file.writeAsBytes(response.data);
await Share.shareXFiles([XFile(file.path)], text: event.caption);
}
Future<void> viewStory(StoryViewEvent event, Emitter emit) async {
var collectionRef = FirebaseFirestore.instance.collection("stories");
if (event.viewMyStory) {
StoryData myStory = state.myStory.copyWith(viewed: true);
await collectionRef.doc(myStory.story.userId).update({"viewed": true});
emit(StoryViewedState(state.posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, myStory));
} else {
List<StoryData> stories = List.from(state.stories);
stories[event.index!] =
StoryData(story: stories[event.index!].story, viewed: true);
await collectionRef
.doc(stories[event.index!].story.userId)
.update({"viewed": true});
emit(StoryViewedState(state.posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, stories, state.myStory));
}
}
Future<void> unfollow(UnFollowFeedEvent event, Emitter emit) async {
emit(UnFollowingFeedState(state.posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
var collectionRef = FirebaseFirestore.instance.collection("users");
if (event.fromFeed) {
String userId = state.posts[event.index!].userId;
var docSnapshot = await collectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List followers = userData.followers;
followers.remove(myUserId);
await collectionRef
.doc(userId)
.update(userData.copyWith(followers: followers).toJson());
List following = state.myData.following;
following.remove(userId);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(UnFollowedUserFeedState(state.posts, myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
} else {
List followers = state.userData.followers;
followers.remove(myUserId);
UserData userData = state.userData.copyWith(followers: followers);
await collectionRef.doc(userData.id).update(userData.toJson());
List following = state.myData.following;
following.remove(userData.id);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(UnFollowedUserFeedState(state.posts, myData, userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
}
}
Future<void> follow(FollowFeedEvent event, Emitter emit) async {
emit(FollowingFeedState(state.posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
String? username = sharedPreferences.getString("username");
String? userProfilePhotoUrl =
sharedPreferences.getString("profilePhotoUrl");
var collectionRef = FirebaseFirestore.instance.collection("users");
if (event.fromFeed) {
String userId = state.posts[event.index!].userId;
var docSnapshot = await collectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List followers = userData.followers;
followers.add(myUserId);
await collectionRef
.doc(userId)
.update(userData.copyWith(followers: followers).toJson());
List following = state.myData.following;
following.add(userId);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(FollowedUserFeedState(state.posts, myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
} else {
List followers = state.userData.followers;
followers.add(myUserId);
UserData userData = state.userData.copyWith(followers: followers);
await collectionRef.doc(userData.id).update(userData.toJson());
List following = state.myData.following;
following.add(userData.id);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(FollowedUserFeedState(state.posts, myData, userData, state.tabIndex,
state.postsIndex, state.stories, state.myStory));
}
String title = "New Follower";
String imageUrl = "";
String body = "$username started following you";
var userData = await collectionRef
.doc(event.fromFeed
? state.posts[event.index!].userId
: state.userData.id)
.get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService()
.sendNotification(title, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
userProfilePhotoUrl!,
DateTime.now().toString(),
myUserId!,
);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
Future<void> deleteMyStory(DeleteMyStory event, Emitter emit) async {
UserData myData = state.myData.copyWith(addedStory: false);
StoryData myStory = StoryData(story: Story.temp(), viewed: false);
emit(MyStoryDeletedState(state.posts, myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, myStory));
}
Future<void> getMyStory(GetMyStory event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
var docSnapshot = await FirebaseFirestore.instance
.collection("stories")
.doc(myUserId)
.get();
var docData = docSnapshot.data()!;
StoryData myStory = StoryData(
story: Story.fromJson(docData["previous_stories"].last), viewed: false);
UserData myData = state.myData.copyWith(addedStory: true);
emit(MyStoryFetchedState(state.posts, myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, myStory));
}
Future<void> fetchUserData(FetchUserData event, Emitter emit) async {
emit(UserDataLoadingState(state.posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
String userId = event.userId;
var docSnapshot =
await FirebaseFirestore.instance.collection("users").doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
emit(UserDataFetchedState(state.posts, state.myData, userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
}
Future<void> addBookmark(BookmarkFeed event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
List bookmarks = List.from(state.myData.bookmarks);
String postId = event.inFeed
? state.posts[event.postIndex].id
: state.userData.posts[event.postIndex].id;
if (bookmarks.contains(postId)) {
bookmarks.remove(postId);
} else {
bookmarks.add(postId);
}
UserData myData = state.myData.copyWith(bookmarks: bookmarks);
await FirebaseFirestore.instance
.collection("users")
.doc(myUserId)
.update(myData.toJson());
emit(BookmarkedState(state.posts, myData, state.userData, state.tabIndex,
state.postsIndex, state.stories, state.myStory));
}
Future<void> deleteComment(DeleteFeedComment event, Emitter emit) async {
List<Post> posts =
event.inFeed ? List.from(state.posts) : List.from(state.userData.posts);
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
String userId = posts[event.postIndex].userId;
var collectionRef = firebaseFirestore.collection("users");
var docRef = collectionRef.doc(userId);
var documentSnapshot = await docRef.get();
var documentData = documentSnapshot.data()!;
for (int i = 0; i < documentData["posts"].length; i++) {
if (documentData["posts"][i]['id'] == posts[event.postIndex].id) {
List comments = documentData["posts"][i]['comments'];
for (int j = 0; j < comments.length; j++) {
if (comments[j]['id'] ==
posts[event.postIndex].comments[event.commentIndex].id) {
comments.removeAt(j);
documentData["posts"][i]['comments'] = comments;
}
}
}
}
List<Comments> comments = posts[event.postIndex].comments;
comments.removeAt(event.commentIndex);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: comments);
await docRef.update(documentData);
if (event.inFeed) {
emit(CommentDeletedState(posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
} else {
UserData userData = state.userData.copyWith(posts: posts);
emit(CommentDeletedState(state.posts, state.myData, userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
}
}
Future<void> addComment(AddFeedComment event, Emitter emit) async {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
var userProfilePhotoUrl = sharedPreferences.getString("profilePhotoUrl");
var collectionRef = firebaseFirestore.collection("users");
String? profilePhotoUrl = sharedPreferences.getString('profilePhotoUrl');
String? username = sharedPreferences.getString('username');
String? myUserId = sharedPreferences.getString("userId");
String id = const Uuid().v4();
Comments newComment =
Comments(event.comment, profilePhotoUrl, username, myUserId, id);
List<Comments> existingComments = event.comments;
existingComments.add(newComment);
if (event.inFeed) {
List<Post> posts = List.from(state.posts);
posts[event.postIndex].comments = existingComments;
String userId = posts[event.postIndex].userId;
var docRef = collectionRef.doc(userId);
var documentSnapshot = await docRef.get();
var documentData = documentSnapshot.data()!;
for (int i = 0; i < documentData["posts"].length; i++) {
if (documentData["posts"][i]["id"] == posts[event.postIndex].id) {
List comments = [];
for (Comments element in existingComments) {
comments.add(element.toJson());
}
documentData["posts"][i]['comments'] = comments;
}
}
await docRef.update(documentData);
emit(CommentAddedState(posts, state.myData, state.userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
} else {
List<Post> posts = List.from(state.userData.posts);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingComments);
UserData userData = state.userData.copyWith(posts: posts);
String userId = posts[event.postIndex].userId;
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(CommentAddedState(state.posts, state.myData, userData,
state.tabIndex, state.postsIndex, state.stories, state.myStory));
}
String title = "Comment";
String imageUrl = event.inFeed
? state.posts[event.postIndex].imageUrl
: state.userData.posts[event.postIndex].imageUrl;
String body = "$username commented on your photo";
var userData = await collectionRef
.doc(event.inFeed
? state.posts[event.postIndex].userId
: state.userData.posts[event.postIndex].userId)
.get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService()
.sendNotification(title, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
userProfilePhotoUrl!,
DateTime.now().toString(),
myUserId!,
);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
Future<void> likePost(PostLikeEvent event, Emitter emit) async {
bool liked = false;
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
String? username = sharedPreferences.getString("username");
String? userProfilePhotoUrl =
sharedPreferences.getString("profilePhotoUrl");
var firestore = FirebaseFirestore.instance;
var collectionRef = firestore.collection("users");
List<Post> posts =
event.inFeed ? List.from(state.posts) : List.from(state.userData.posts);
List likes = posts[event.index].likes;
if (likes.contains(userId)) {
likes.remove(userId);
liked = false;
} else {
likes.add(userId);
liked = true;
}
posts[event.index] = posts[event.index].copyWith(likes: likes);
var docSnapshot = await collectionRef.doc(event.userId).get();
List<Post> userPosts = UserData.fromJson(docSnapshot.data()!).posts;
for (int i = 0; i < userPosts.length; i++) {
if (userPosts[i].id == event.postId) {
if (event.inFeed) {
UserData userdata = UserData.fromJson(docSnapshot.data()!);
userPosts[i] = userPosts[i].copyWith(likes: likes);
await collectionRef
.doc(event.userId)
.update(userdata.copyWith(posts: userPosts).toJson());
} else {
userPosts[i] = userPosts[i].copyWith(likes: likes);
UserData userData = state.userData.copyWith(posts: userPosts);
await collectionRef.doc(event.userId).update(userData.toJson());
}
}
}
if (event.inFeed) {
emit(PostLikedState(posts, state.myData, state.userData, state.tabIndex,
state.postsIndex, state.stories, state.myStory));
} else {
UserData userData = state.userData.copyWith(posts: posts);
emit(PostLikedState(state.posts, state.myData, userData, state.tabIndex,
state.postsIndex, state.stories, state.myStory));
}
if (liked) {
String title = "Like";
String imageUrl = posts[event.index].imageUrl;
String body = "$username liked your photo";
var userData = await collectionRef.doc(posts[event.index].userId).get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService()
.sendNotification(title, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
userProfilePhotoUrl!,
DateTime.now().toString(),
userId!);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
}
Future<void> getPosts(GetFeed event, Emitter emit) async {
emit(FeedInitial(const <Post>[], UserData.temp(), UserData.temp(), 0, 0,
const [], StoryData(story: Story.temp(), viewed: false)));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString('userId');
var firestoreCollectionRef = FirebaseFirestore.instance.collection("users");
var docSnapshot = await firestoreCollectionRef.doc(userId).get();
UserData myData = UserData.fromJson(docSnapshot.data()!);
var result =
await firestoreCollectionRef.where("id", isNotEqualTo: userId).get();
var docsList = result.docs;
List<Post> posts = [];
for (int i = 0; i < docsList.length; i++) {
List postsList = docsList[i].data()['posts'];
for (int j = 0; j < postsList.length; j++) {
posts.add(Post.fromJson(postsList[j]));
}
}
if (event.atStart) {
posts.shuffle();
}
var storiesCollectionRef = FirebaseFirestore.instance.collection("stories");
String todaysDate = DateTime.now().toString().split(" ")[0];
StoryData myStory = StoryData(story: Story.temp(), viewed: false);
if (myData.addedStory) {
var storySnapshot = await storiesCollectionRef.doc(userId).get();
if (storySnapshot.data()!['previous_stories'].last['date'] !=
todaysDate) {
myData = myData.copyWith(addedStory: false);
myStory = StoryData(story: Story.temp(), viewed: false);
await storiesCollectionRef.doc(userId).update({"addedStory": false});
await firestoreCollectionRef.doc(userId).update({"addedStory": false});
} else {
myStory = StoryData(
story:
Story.fromJson(storySnapshot.data()!["previous_stories"].last),
viewed: storySnapshot.data()!['viewed']);
}
}
var peopleAddedStoriesSnapshot = await storiesCollectionRef
.where("addedStory", isEqualTo: true)
.where("userId", isNotEqualTo: userId)
.get();
var peopleAddedStoryDocs = peopleAddedStoriesSnapshot.docs;
List<StoryData> stories = [];
for (int i = 0; i < peopleAddedStoryDocs.length; i++) {
if (peopleAddedStoryDocs[i].data()['previous_stories'].last['date'] ==
todaysDate) {
stories.add(StoryData(
story: Story.fromJson(
peopleAddedStoryDocs[i].data()["previous_stories"].last),
viewed: peopleAddedStoryDocs[i].data()['viewed']));
}
}
emit(FeedFetched(
posts,
myData,
state.userData,
state.tabIndex,
state.postsIndex,
stories,
myStory,
));
for (int i = 0; i < peopleAddedStoryDocs.length; i++) {
if (peopleAddedStoryDocs[i].data()['previous_stories'].last['date'] !=
todaysDate) {
await FirebaseFirestore.instance
.collection("users")
.doc(peopleAddedStoryDocs[i].id)
.update({"addedStory": false});
await FirebaseFirestore.instance
.collection("stories")
.doc(peopleAddedStoryDocs[i].id)
.update({"addedStory": false});
}
}
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story/view_story.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/data/stories.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/story/bloc/story_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';
class ViewStoryPage extends StatelessWidget {
const ViewStoryPage(
{super.key,
required this.story,
required this.inProfile,
required this.index,
required this.inSearchProfile});
final Story story;
final bool inProfile;
final int index;
final bool inSearchProfile;
Widget buildBottomSheet(BuildContext context, double height, double width) {
return SizedBox(
height: height * 0.15,
child: Padding(
padding: const EdgeInsets.only(
top: 16.0,
bottom: 16.0,
),
child: Column(
children: [
ListTile(
minLeadingWidth: 0,
leading: Icon(
Icons.delete_outline,
color: instaRed,
),
title: InstaText(
fontSize: 17,
color: instaRed,
fontWeight: FontWeight.normal,
text: inProfile ? "Delete Highlight" : "Delete Story",
),
onTap: () {
// update myData addedstory false in feed and firestore
if (inProfile) {
context.read<ProfileBloc>().add(DeleteHighlight(index));
} else if (inSearchProfile) {
context
.read<SearchBloc>()
.add(DeleteSearchProfileHighlight(index: index));
} else {
context.read<StoryBloc>().add(DeleteStory());
}
Navigator.of(context).pop();
},
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
var sharedPreferences = context.read<HomepageBloc>().sharedPreferences;
return BlocConsumer<SearchBloc, SearchState>(
listener: (context, searchState) {
if (searchState is DeletedHighLightSearchState) {
Navigator.of(context).pop();
}
},
builder: (context, searchState) {
return BlocConsumer<ProfileBloc, ProfileState>(
listener: (context, profileState) {
if (profileState is HighlightDeleted) {
Navigator.of(context).pop();
}
},
builder: (context, profileState) {
return BlocConsumer<StoryBloc, StoryState>(
listener: (context, storyState) {
if (storyState is StoryDeleted) {
var bloc = context.read<FeedBloc>();
bloc.add(DeleteMyStory());
Navigator.of(context).pop();
}
}, builder: (context, storyState) {
return Scaffold(
backgroundColor: Colors.black,
body: Stack(alignment: Alignment.center, children: [
SafeArea(
child: Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
ProfilePhoto(
height: height * 0.06,
width: height * 0.065,
wantBorder: false,
storyAdder: false,
imageUrl: story.userProfilePhotoUrl,
),
SizedBox(
width: width * 0.02,
),
InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w700,
text: story.username,
),
],
),
),
story.userId == sharedPreferences.getString("userId")!
? IconButton(
onPressed: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10)),
backgroundColor: Colors.black,
context: context,
builder: ((_) => BlocProvider.value(
value: context.read<StoryBloc>(),
child: buildBottomSheet(
context, height, width),
)));
},
icon: const Icon(
Icons.more_vert,
color: Colors.white,
),
)
: Container(),
],
),
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: CachedNetworkImage(
width: double.infinity,
imageUrl: story.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: InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w600,
text: story.caption),
),
]),
),
(storyState is DeletingStoryState ||
profileState is DeletingHighLight ||
searchState is DeletingHighLightSearchState)
? 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,
),
InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w500,
text: inProfile
? "Deleting Highlight"
: "Deleting Story")
],
)),
)
: Container()
]),
);
});
},
);
},
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story/add_story.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/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/story/bloc/story_bloc.dart';
import 'package:instagram_clone/widgets/insta_button.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import 'package:instagram_clone/widgets/instatext.dart';
class AddStoryPage extends StatefulWidget {
const AddStoryPage({super.key});
@override
State<AddStoryPage> createState() => _AddStoryPageState();
}
class _AddStoryPageState extends State<AddStoryPage> {
final TextEditingController captionController = TextEditingController();
@override
void dispose() {
captionController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
return WillPopScope(
onWillPop: () async {
var bloc = context.read<StoryBloc>();
if (bloc.state is StoryInitial) {
return true;
} else {
bloc.add(CancelEvent());
return false;
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.black,
title: const InstaText(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w700,
text: "Add to story"),
leading: IconButton(
onPressed: () {
var bloc = context.read<StoryBloc>();
if (bloc.state is StoryInitial) {
Navigator.of(context).pop();
} else {
bloc.add(CancelEvent());
}
},
icon: const Icon(Icons.arrow_back_ios),
),
),
body: BlocListener<StoryBloc, StoryState>(
listener: (context, state) {
if (state is StoryPosted) {
var feedbloc = context.read<FeedBloc>();
feedbloc.add(GetMyStory());
Navigator.of(context).pop();
}
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: BlocBuilder<StoryBloc, StoryState>(
builder: (context, state) {
if (state is StoryInitial) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "Add Story on Instagram",
),
SizedBox(
height: height * 0.05,
),
InstaButton(
borderWidth: 1,
width: width,
postButton: true,
onPressed: () {
context
.read<StoryBloc>()
.add(const ChooseImageEvent(false));
},
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<StoryBloc>()
.add(const ChooseImageEvent(true));
},
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 StoryReadyState ||
state is StoryPostingState) {
return Column(
children: [
Expanded(
child: Image.file(
fit: BoxFit.cover,
width: width,
File(state.imagePath),
),
),
SizedBox(
height: height * 0.04,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: captionController,
hintText: "Story 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,
),
state is StoryPostingState
? const Align(
alignment: Alignment.center,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
)
: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InstaButton(
borderWidth: 1,
width: width * 0.4,
onPressed: () {
context
.read<StoryBloc>()
.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;
context
.read<StoryBloc>()
.add(PostStory(caption));
},
text: "Post",
fontSize: 14,
textColor: Colors.black,
fontWeight: FontWeight.w700,
buttonColor: Colors.white,
height: height * 0.05,
postButton: true),
],
)
],
);
} else {
return Container();
}
},
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story/bloc/story_state.dart | part of 'story_bloc.dart';
abstract class StoryState extends Equatable {
const StoryState(this.imagePath);
final String imagePath;
@override
List<Object> get props => [];
}
class StoryInitial extends StoryState {
const StoryInitial(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class StoryReadyState extends StoryState {
const StoryReadyState(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class StoryPosted extends StoryState {
const StoryPosted(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class StoryPostingState extends StoryState {
const StoryPostingState(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class StoryDeleted extends StoryState {
const StoryDeleted(super.imagePath);
@override
List<Object> get props => [imagePath];
}
class DeletingStoryState extends StoryState {
const DeletingStoryState(super.imagePath);
@override
List<Object> get props => [imagePath];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story/bloc/story_bloc.dart | import 'dart:io';
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_clone/data/stories.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 'story_event.dart';
part 'story_state.dart';
class StoryBloc extends Bloc<StoryEvent, StoryState> {
StoryBloc() : super(const StoryInitial("")) {
on<ChooseImageEvent>((event, emit) => chooseImage(event, emit));
on<CancelEvent>((event, emit) => emit(const StoryInitial("")));
on<PostStory>((event, emit) => postStory(event, emit));
on<DeleteStory>((event, emit) => deleteStory(event, emit));
}
Future<void> deleteStory(DeleteStory event, Emitter emit) async {
emit(const DeletingStoryState(""));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update({"addedStory": false});
var collectionRef = FirebaseFirestore.instance.collection("stories");
var docSnapshot = await collectionRef.doc(userId).get();
var docData = docSnapshot.data()!;
List previousStories = docData['previous_stories'];
previousStories.removeLast();
await collectionRef
.doc(userId)
.update({"previous_stories": previousStories, "addedStory": false});
emit(const StoryDeleted(""));
}
Future<void> chooseImage(ChooseImageEvent event, Emitter emit) async {
var image = await ImagePicker().pickImage(
source: event.fromGallery ? ImageSource.gallery : ImageSource.camera);
if (image != null) {
emit(StoryReadyState(image.path));
} else {
emit(const StoryInitial(""));
}
}
Future<void> postStory(PostStory event, Emitter emit) async {
int id = Random().nextInt(100000);
try {
emit(StoryPostingState(state.imagePath));
sendNotification(id);
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
String? userProfilePhotoUrl =
sharedPreferences.getString("profilePhotoUrl");
String? username = sharedPreferences.getString("username");
String storyId = const Uuid().v4();
String caption = event.caption;
String date = DateTime.now().toString().split(" ")[0];
var firebaseStorageRef = FirebaseStorage.instance.ref();
var childRef = firebaseStorageRef.child(userId!);
String hash = const Uuid().v4();
String imageName = "stories/story$hash.jpg";
var imageLocationRef = childRef.child(imageName);
File image = File(state.imagePath);
await imageLocationRef.putFile(image);
var imageUrl = await imageLocationRef.getDownloadURL();
Story story = Story(
id: storyId,
userProfilePhotoUrl: userProfilePhotoUrl!,
username: username!,
imageUrl: imageUrl,
caption: caption,
userId: userId,
date: date);
var collectionRef = FirebaseFirestore.instance.collection("stories");
var docSnapshot = await collectionRef.doc(userId).get();
var docData = docSnapshot.data();
if (docData == null) {
await collectionRef.doc(userId).set({
"addedStory": false,
"userId": userId,
"previous_stories": [],
"viewed": false,
});
}
List previousStories = docData == null ? [] : docData["previous_stories"];
previousStories.add(story.toJson());
await collectionRef
.doc(userId)
.update({"previous_stories": previousStories, "addedStory": true});
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update({"addedStory": true});
flutterLocalNotificationsPlugin.cancel(id);
emit(const StoryPosted(""));
String title = "New Story";
String notificationImageUrl = "";
String body = "$username added to their story";
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 StoryInitial(""));
}
}
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/feed/story | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/feed/story/bloc/story_event.dart | part of 'story_bloc.dart';
abstract class StoryEvent extends Equatable {
const StoryEvent();
@override
List<Object> get props => [];
}
class ChooseImageEvent extends StoryEvent {
final bool fromGallery;
const ChooseImageEvent(this.fromGallery);
@override
List<Object> get props => [fromGallery];
}
class CancelEvent extends StoryEvent {}
class PostStory extends StoryEvent {
final String caption;
const PostStory(this.caption);
@override
List<Object> get props => [caption];
}
class DeleteStory extends StoryEvent {}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search/user_profile.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/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/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'
as p;
import 'package:instagram_clone/pages/homepage/homepage_pages/search/bloc/search_bloc.dart';
import 'package:instagram_clone/widgets/insta_button.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'package:instagram_clone/widgets/profile_photo.dart';
class UserProfilePage extends StatefulWidget {
const UserProfilePage(
{super.key, required this.pageController, required this.inSearch});
final PageController pageController;
final bool inSearch;
@override
State<UserProfilePage> createState() => _UserProfilePageState();
}
class _UserProfilePageState extends State<UserProfilePage>
with SingleTickerProviderStateMixin {
late final TabController tabController;
@override
void initState() {
super.initState();
tabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
tabController.dispose();
super.dispose();
}
Widget buildBottomSheet(
BuildContext context, double height, double width, bool inSearch) {
return SizedBox(
height: height * 0.15,
child: Padding(
padding: const EdgeInsets.only(
top: 16.0,
bottom: 16.0,
),
child: Column(
children: [
ListTile(
minLeadingWidth: 0,
leading: const Icon(
Icons.person_remove,
color: Colors.white,
),
title: const InstaText(
fontSize: 17,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Unfollow",
),
onTap: () {
if (inSearch) {
context
.read<SearchBloc>()
.add(const UnFollowSearchEvent(fromProfile: true));
} else {
context
.read<FeedBloc>()
.add(const UnFollowFeedEvent(fromFeed: false));
}
Navigator.of(context).pop();
},
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
var homePageBloc = context.read<HomepageBloc>();
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return BlocBuilder<FeedBloc, FeedState>(
builder: (context, FeedState feedState) {
return BlocBuilder<SearchBloc, SearchState>(
bloc: context.read<SearchBloc>(),
builder: (context, SearchState searchState) {
if (!widget.inSearch && feedState is UserDataLoadingState) {
return const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
);
} else if (widget.inSearch &&
(searchState is LoadingUserDataSearchState ||
searchState is LoadingUserProfileState)) {
return const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
);
} else {
return Scaffold(
backgroundColor: textFieldBackgroundColor,
appBar: AppBar(
backgroundColor: textFieldBackgroundColor,
leading: IconButton(
onPressed: () async {
if (widget.inSearch) {
if (searchState.previousPage == 1) {
context
.read<SearchBloc>()
.add(UserProfileBackEvent());
widget.pageController.jumpToPage(1);
} else if (searchState.previousPage == 2) {
widget.pageController.jumpToPage(1);
context.read<SearchBloc>().add(GetPosts());
}
} else {
var bloc = context.read<FeedBloc>();
bloc.add(const GetFeed(false));
widget.pageController.jumpToPage(0);
}
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
),
title: InstaText(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.w700,
text: widget.inSearch
? searchState.userData.username
: feedState.userData.username,
),
),
body: SingleChildScrollView(
child: SizedBox(
height: height - 2.5 * AppBar().preferredSize.height,
width: width,
child: 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: widget.inSearch
? searchState.userData.profilePhotoUrl
: feedState.userData.profilePhotoUrl,
),
SizedBox(
width: width * 0.1,
),
Row(
children: [
Column(
children: [
InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: widget.inSearch
? searchState
.userData.posts.length
.toString()
: feedState
.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: widget.inSearch
? searchState
.userData.followers.length
.toString()
: feedState
.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: widget.inSearch
? searchState
.userData.following.length
.toString()
: feedState
.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: widget.inSearch
? searchState.userData.name
: feedState.userData.name,
),
SizedBox(
height: height * 0.003,
),
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.normal,
text: widget.inSearch
? searchState.userData.bio
: feedState.userData.bio),
SizedBox(
height: height * 0.003,
),
InstaText(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.normal,
text: widget.inSearch
? searchState.userData.tagline
: feedState.userData.tagline,
),
],
),
),
SizedBox(
height: height * 0.02,
),
widget.inSearch
? (searchState is FollowingSearchState ||
searchState
is UnFollowingSearchState)
? SizedBox(
height: height * 0.05,
child: const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
),
)
: searchState.userData.followers
.contains(homePageBloc
.sharedPreferences
.getString("userId"))
? SizedBox(
height: height * 0.05,
child: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
InstaButton(
borderWidth: 1,
width: width * 0.43,
postButton: false,
height: height * 0.05,
buttonColor: Colors.black,
onPressed: () async {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
10)),
backgroundColor:
Colors.black,
context: context,
builder: (_) =>
buildBottomSheet(
context,
height,
width,
true,
));
},
text: "following",
fontSize: 13,
textColor: Colors.white,
fontWeight:
FontWeight.w700,
),
InstaButton(
borderWidth: 1,
width: width * 0.43,
postButton: false,
height: height * 0.05,
buttonColor: Colors.black,
onPressed: () async {},
text: "message",
fontSize: 13,
textColor: Colors.white,
fontWeight:
FontWeight.w700,
)
],
))
: searchState.userData.id !=
homePageBloc
.sharedPreferences
.getString("userId")
? InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.05,
buttonColor: instablue,
onPressed: () async {
context
.read<SearchBloc>()
.add(
const FollowSearchEvent(
fromProfile:
true));
},
text: "Follow",
fontSize: 13,
textColor: Colors.white,
fontWeight: FontWeight.w700,
)
: Container()
: (feedState is FollowingFeedState ||
feedState is UnFollowingFeedState)
? SizedBox(
height: height * 0.05,
child: const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
),
)
: feedState.userData.followers.contains(
homePageBloc.sharedPreferences
.getString("userId"))
? SizedBox(
height: height * 0.05,
child: Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
InstaButton(
borderWidth: 1,
width: width * 0.43,
postButton: false,
height: height * 0.05,
buttonColor: Colors.black,
onPressed: () async {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
10)),
backgroundColor:
Colors.black,
context: context,
builder: (_) =>
buildBottomSheet(
context,
height,
width,
false,
));
},
text: "following",
fontSize: 13,
textColor: Colors.white,
fontWeight:
FontWeight.w700,
),
InstaButton(
borderWidth: 1,
width: width * 0.43,
postButton: false,
height: height * 0.05,
buttonColor: Colors.black,
onPressed: () async {},
text: "message",
fontSize: 13,
textColor: Colors.white,
fontWeight:
FontWeight.w700,
)
],
))
: feedState.userData.id !=
homePageBloc
.sharedPreferences
.getString("userId")
? InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.05,
buttonColor: instablue,
onPressed: () async {
context.read<FeedBloc>().add(
const FollowFeedEvent(
fromFeed: false));
},
text: "Follow",
fontSize: 13,
textColor: Colors.white,
fontWeight: FontWeight.w700,
)
: Container(),
],
),
),
((widget.inSearch
? searchState.userData.private
: feedState.userData.private) &&
(widget.inSearch
? (searchState.userData.id !=
homePageBloc.sharedPreferences
.getString("userId"))
: (feedState.userData.id !=
homePageBloc.sharedPreferences
.getString("userId")))) &&
(widget.inSearch
? !searchState.userData.followers
.contains(homePageBloc
.sharedPreferences
.getString("userId"))
: !feedState.userData.followers.contains(
homePageBloc.sharedPreferences
.getString("userId")))
? Column(
children: [
SizedBox(
height: height * 0.1,
),
Container(
height: height * 0.15,
width: height * 0.15,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white, width: 2),
),
child: Center(
child: Image.asset(
"assets/images/lock_icon.png",
),
),
),
SizedBox(
height: height * 0.02,
),
const InstaText(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "This Account",
),
const InstaText(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.bold,
text: "is Private",
),
SizedBox(
height: height * 0.01,
),
InstaText(
fontSize: 14,
color: Colors.white.withOpacity(0.7),
fontWeight: FontWeight.normal,
text: "Follow this account to see their",
),
InstaText(
fontSize: 14,
color: Colors.white.withOpacity(0.7),
fontWeight: FontWeight.normal,
text: "photos and videos",
),
],
)
: Expanded(
child: Column(
children: [
(widget.inSearch
? searchState
.userData.stories.isEmpty
: feedState
.userData.stories.isEmpty)
? Container()
: SizedBox(
height: height * 0.01,
),
(widget.inSearch
? searchState
.userData.stories.isEmpty
: feedState
.userData.stories.isEmpty)
? Container()
: Padding(
padding: const EdgeInsets.only(
left: 8.0, right: 8.0),
child: SizedBox(
height: height * 0.12,
width: width,
child: ListView.builder(
scrollDirection:
Axis.horizontal,
itemCount: widget.inSearch
? searchState.userData
.stories.length
: feedState.userData
.stories.length,
itemBuilder:
(context, index) {
return Padding(
padding:
const EdgeInsets.only(
left: 10.5),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
MultiBlocProvider(
providers: [
BlocProvider.value(
value: context.read<SearchBloc>(),
),
BlocProvider.value(value: context.read<HomepageBloc>()),
BlocProvider(create: (context) => p.ProfileBloc(PageController())),
BlocProvider(create: (context) => StoryBloc())
],
child:
ViewStoryPage(
story: widget.inSearch
? searchState.userData.stories[index]
: feedState.userData.stories[index],
inProfile:
false,
index:
index,
inSearchProfile:
true,
))));
},
child: Column(
children: [
ProfilePhoto(
height:
height * 0.1,
width:
height * 0.1,
wantBorder: true,
storyAdder: false,
imageUrl: widget
.inSearch
? searchState
.userData
.stories[
index]
.imageUrl
: feedState
.userData
.stories[
index]
.imageUrl,
),
InstaText(
fontSize: 10,
color:
Colors.white,
fontWeight:
FontWeight
.normal,
text: widget
.inSearch
? searchState
.userData
.stories[
index]
.caption
: feedState
.userData
.stories[
index]
.caption,
)
],
),
),
);
},
),
),
),
SizedBox(
height: height * 0.02,
),
(widget.inSearch
? searchState
.userData.stories.isEmpty
: feedState
.userData.stories.isEmpty)
? Container()
: Divider(
color: profilePhotoBorder,
thickness: 0.5,
),
SizedBox(
height: height * 0.05,
width: double.infinity,
child: TabBar(
onTap: (tabIndex) {
if (widget.inSearch) {
context.read<SearchBloc>().add(
TabChangeEvent(tabIndex));
} else {
context.read<FeedBloc>().add(
TabChangeFeedEvent(
tabIndex));
}
},
indicatorWeight: 1,
indicatorColor: Colors.white,
controller: tabController,
tabs: [
Tab(
icon: SizedBox(
height: height * 0.03,
child: (widget.inSearch
? searchState
.tabIndex ==
0
: feedState
.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: (widget.inSearch
? searchState
.tabIndex ==
1
: feedState
.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: [
(widget.inSearch
? searchState
.userData.posts.isEmpty
: feedState
.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: widget.inSearch
? searchState.userData
.posts.length
: feedState.userData
.posts.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing:
4.0,
mainAxisSpacing:
4.0),
itemBuilder:
((context, index) {
return InkWell(
onTap: () async {
if (widget.inSearch) {
var bloc =
context.read<
SearchBloc>();
bloc.add(
PostsIndexChangeEvent(
index,
true));
await bloc
.pageController
.animateToPage(
2,
duration:
const Duration(
milliseconds:
200),
curve:
Curves.ease,
);
} else {
var bloc =
context.read<
FeedBloc>();
bloc.add(
FeedPostsIndexChangeEvent(
index,
));
await bloc
.pageController
.animateToPage(
2,
duration:
const Duration(
milliseconds:
200),
curve:
Curves.ease,
);
}
},
child:
CachedNetworkImage(
imageUrl: widget
.inSearch
? searchState
.userData
.posts[index]
.imageUrl
: feedState
.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")
],
),
),
],
),
),
],
),
),
],
),
),
),
);
}
});
},
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search/search_page.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/widgets/user_posts.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/search/user_profile.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import 'package:instagram_clone/widgets/instatext.dart';
import 'bloc/search_bloc.dart';
class SearchPage extends StatefulWidget {
const SearchPage({super.key});
@override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
@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<SearchBloc>().pageController,
children: [
BlocProvider.value(
value: context.read<SearchBloc>(),
child: UserProfilePage(
inSearch: true,
pageController: context.read<SearchBloc>().pageController,
),
),
Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
elevation: 0,
backgroundColor: textFieldBackgroundColor,
title: SizedBox(
height: AppBar().preferredSize.height,
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0),
child: InstaTextField(
focusNode: context.read<SearchBloc>().focusNode,
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: searchTextFieldColor,
borderRadius: 15,
icon: Icon(
Icons.search,
color: searchHintText,
),
controller: context.read<SearchBloc>().searchController,
hintText: "Search",
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: searchHintText,
obscureText: false,
onChange: (value) {
if (value.isNotEmpty) {
context.read<SearchBloc>().add(SearchUsers(value));
} else {
context.read<SearchBloc>().add(GetPosts());
}
},
),
),
),
),
body: BlocBuilder<SearchBloc, SearchState>(
builder: (context, state) {
if (state is SearchInitial) {
return const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
);
} else if (state is PostsFetched ||
state is PostIndexChangedSearchState ||
state is LikePostState ||
state is AddedCommentSearchState ||
state is DeletedCommentSearchState ||
state is BookmarkedSearchState ||
state is FollowedUserSearchState ||
state is UnFollowedUserSearchState ||
state is UnFollowingSearchState ||
state is FollowingSearchState ||
state is FetchedUserDataSearchState ||
state is LoadingUserDataSearchState) {
return SizedBox(
width: width,
height: height,
child: GridView.builder(
itemCount: state.posts.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
),
itemBuilder: (context, index) {
return InkWell(
onTap: () async {
var bloc = context.read<SearchBloc>();
bloc.add(PostsIndexChangeEvent(index, false));
await bloc.pageController.animateToPage(
2,
duration: const Duration(milliseconds: 200),
curve: Curves.ease,
);
},
child: CachedNetworkImage(
imageUrl: state.posts[index].imageUrl,
fit: BoxFit.fill,
placeholder: (context, val) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
);
},
),
);
},
),
);
} else if (state is UsersSearched) {
return SizedBox(
height: height,
width: width,
child: ListView.builder(
itemCount: state.usersList.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () async {
FocusManager.instance.primaryFocus?.unfocus();
var bloc = context.read<SearchBloc>();
bloc.add(UserProfileEvent(state.usersList[index]));
await bloc.pageController.animateToPage(0,
duration: const Duration(milliseconds: 200),
curve: Curves.ease);
},
leading: ClipOval(
child: Container(
decoration:
const BoxDecoration(shape: BoxShape.circle),
height: double.maxFinite,
width: width * 0.16,
child: CachedNetworkImage(
imageUrl: state.usersList[index].profilePhotoUrl,
fit: BoxFit.fill,
),
),
),
title: InstaText(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
text: state.usersList[index].username,
),
subtitle: InstaText(
fontSize: 16,
color: Colors.white.withOpacity(0.5),
fontWeight: FontWeight.normal,
text: state.usersList[index].name,
),
);
},
),
);
} else {
return const Center(
child: InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w500,
text: "Search"),
);
}
},
),
),
BlocProvider.value(
value: context.read<SearchBloc>(),
child: const UserPosts(
inProfile: false,
inFeed: false,
),
)
],
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search/bloc/search_event.dart | part of 'search_bloc.dart';
abstract class SearchEvent extends Equatable {
const SearchEvent();
@override
List<Object> get props => [];
}
class GetPosts extends SearchEvent {}
class SearchUsers extends SearchEvent {
final String text;
const SearchUsers(this.text);
@override
List<Object> get props => [text];
}
class UserProfileEvent extends SearchEvent {
final UserData userData;
const UserProfileEvent(this.userData);
@override
List<Object> get props => [userData];
}
class UserProfileBackEvent extends SearchEvent {}
class TabChangeEvent extends SearchEvent {
final int tabIndex;
const TabChangeEvent(this.tabIndex);
@override
List<Object> get props => [tabIndex];
}
class PostsIndexChangeEvent extends SearchEvent {
final int postIndex;
final bool usersPosts;
const PostsIndexChangeEvent(this.postIndex, this.usersPosts);
@override
List<Object> get props => [postIndex, usersPosts];
}
class SearchLikePostEvent extends SearchEvent {
final int postIndex;
final bool userPosts;
final String userId;
final String postId;
const SearchLikePostEvent(
this.postIndex, this.userPosts, this.userId, this.postId);
@override
List<Object> get props => [postIndex, userPosts, userId, postId];
}
class ShareSearchFileEvent extends SearchEvent {
final String imageUrl;
final String caption;
const ShareSearchFileEvent({required this.caption, required this.imageUrl});
@override
List<Object> get props => [imageUrl];
}
class DeleteSearchComment extends SearchEvent {
final int postIndex;
final int commentIndex;
const DeleteSearchComment(this.postIndex, this.commentIndex);
@override
List<Object> get props => [postIndex, commentIndex];
}
class AddSearchComment extends SearchEvent {
final List<Comments> comments;
final int postIndex;
final String comment;
const AddSearchComment(this.comments, this.postIndex, this.comment);
@override
List<Object> get props => [comments, postIndex, comment];
}
class BookmarkSearch extends SearchEvent {
final int postIndex;
const BookmarkSearch(this.postIndex);
@override
List<Object> get props => [postIndex];
}
class DeleteSearchProfilePost extends SearchEvent {
final int index;
const DeleteSearchProfilePost(this.index);
@override
List<Object> get props => [index];
}
class FollowSearchEvent extends SearchEvent {
final bool fromProfile;
final int? index;
const FollowSearchEvent({required this.fromProfile, this.index});
@override
List<Object> get props => [fromProfile];
}
class UnFollowSearchEvent extends SearchEvent {
final bool fromProfile;
final int? index;
const UnFollowSearchEvent({required this.fromProfile, this.index});
@override
List<Object> get props => [fromProfile];
}
class FetchUserDataInSearch extends SearchEvent {
final String userId;
const FetchUserDataInSearch({required this.userId});
@override
List<Object> get props => [userId];
}
class DeleteSearchProfileHighlight extends SearchEvent {
final int index;
const DeleteSearchProfileHighlight({required this.index});
@override
List<Object> get props => [index];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search/bloc/search_state.dart | part of 'search_bloc.dart';
abstract class SearchState extends Equatable {
const SearchState(this.posts, this.usersList, this.userData, this.tabIndex,
this.postsIndex, this.usersPosts, this.myData, this.previousPage);
final List<Post> posts;
final List<UserData> usersList;
final UserData userData;
final UserData myData;
final int postsIndex;
final int tabIndex;
final bool usersPosts;
final int previousPage;
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class SearchInitial extends SearchState {
const SearchInitial(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class PostsFetched extends SearchState {
const PostsFetched(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class UsersSearched extends SearchState {
const UsersSearched(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class UserProfileState extends SearchState {
const UserProfileState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class TabChangeState extends SearchState {
const TabChangeState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class PostIndexChangedSearchState extends SearchState {
const PostIndexChangedSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class LikePostState extends SearchState {
const LikePostState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class AddedCommentSearchState extends SearchState {
const AddedCommentSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class DeletedCommentSearchState extends SearchState {
const DeletedCommentSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class BookmarkedSearchState extends SearchState {
const BookmarkedSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class DeletedSearchProfilePostState extends SearchState {
const DeletedSearchProfilePostState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class FollowingSearchState extends SearchState {
const FollowingSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class FollowedUserSearchState extends SearchState {
const FollowedUserSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class UnFollowedUserSearchState extends SearchState {
const UnFollowedUserSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class UnFollowingSearchState extends SearchState {
const UnFollowingSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class FetchedUserDataSearchState extends SearchState {
const FetchedUserDataSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class LoadingUserDataSearchState extends SearchState {
const LoadingUserDataSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class DeletedHighLightSearchState extends SearchState {
const DeletedHighLightSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class DeletingHighLightSearchState extends SearchState {
const DeletingHighLightSearchState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
class LoadingUserProfileState extends SearchState {
const LoadingUserProfileState(
super.posts,
super.usersList,
super.userData,
super.tabIndex,
super.postsIndex,
super.usersPosts,
super.myData,
super.previousPage);
@override
List<Object> get props => [
posts,
usersList,
userData,
tabIndex,
postsIndex,
usersPosts,
myData,
previousPage
];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search | mirrored_repositories/instagram_clone/lib/pages/homepage/homepage_pages/search/bloc/search_bloc.dart | import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:instagram_clone/data/comment_data.dart';
import 'package:instagram_clone/data/notification_data.dart';
import 'package:instagram_clone/data/posts_data.dart';
import 'package:instagram_clone/data/stories.dart';
import 'package:instagram_clone/data/user_data.dart';
import 'package:instagram_clone/utility/notification_service.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
part 'search_event.dart';
part 'search_state.dart';
class SearchBloc extends Bloc<SearchEvent, SearchState> {
final PageController pageController;
final FocusNode focusNode;
final TextEditingController searchController;
SearchBloc(this.pageController, this.focusNode, this.searchController)
: super(SearchInitial(const <Post>[], const <UserData>[], UserData.temp(),
0, 0, true, UserData.temp(), 1)) {
on<GetPosts>((event, emit) => getPosts(event, emit));
on<SearchUsers>((event, emit) => searchUsers(event, emit));
on<UserProfileEvent>((event, emit) => getUserProfileData(event, emit));
on<UserProfileBackEvent>((event, emit) => emit(UsersSearched(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
0)));
on<TabChangeEvent>((event, emit) => emit(TabChangeState(
state.posts,
state.usersList,
state.userData,
event.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage)));
on<PostsIndexChangeEvent>((event, emit) => emit(PostIndexChangedSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
event.postIndex,
event.usersPosts,
state.myData,
state.previousPage,
)));
on<SearchLikePostEvent>((event, emit) => likePost(event, emit));
on<AddSearchComment>((event, emit) => addComment(event, emit));
on<DeleteSearchComment>((event, emit) => deleteComment(event, emit));
on<BookmarkSearch>((event, emit) => addBookmark(event, emit));
on<DeleteSearchProfilePost>((event, emit) => deletePost(event, emit));
on<FollowSearchEvent>((event, emit) => follow(event, emit));
on<UnFollowSearchEvent>((event, emit) => unfollow(event, emit));
on<FetchUserDataInSearch>((event, emit) => fetchUserData(event, emit));
on<ShareSearchFileEvent>((event, emit) => shareFile(event, emit));
on<DeleteSearchProfileHighlight>(
(event, emit) => deleteSearchProfileHightlight(event, emit));
}
Future<void> getUserProfileData(UserProfileEvent event, Emitter emit) async {
emit(LoadingUserProfileState(state.posts, state.usersList, state.userData,
state.tabIndex, state.postsIndex, state.usersPosts, state.myData, 1));
String userId = event.userData.id;
var snapshot =
await FirebaseFirestore.instance.collection("users").doc(userId).get();
UserData userData = UserData.fromJson(snapshot.data()!);
emit(UserProfileState(state.posts, state.usersList, userData,
state.tabIndex, state.postsIndex, state.usersPosts, state.myData, 1));
}
Future<void> deleteSearchProfileHightlight(
DeleteSearchProfileHighlight event, Emitter emit) async {
emit(DeletingHighLightSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
List<Story> hightlights = List.from(state.myData.stories);
hightlights.removeAt(event.index);
UserData userData = state.userData.copyWith(stories: hightlights);
await FirebaseFirestore.instance
.collection('users')
.doc(userId)
.update(userData.toJson());
emit(DeletedHighLightSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
userData,
state.previousPage));
}
Future<void> shareFile(ShareSearchFileEvent event, Emitter emit) async {
var response = await Dio().get(event.imageUrl,
options: Options(responseType: ResponseType.bytes));
Directory dir = await getTemporaryDirectory();
File file = File('${dir.path}/image.png');
await file.writeAsBytes(response.data);
await Share.shareXFiles([XFile(file.path)], text: event.caption);
}
Future<void> fetchUserData(FetchUserDataInSearch event, Emitter emit) async {
emit(LoadingUserDataSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
2));
String userId = event.userId;
var docSnapshot =
await FirebaseFirestore.instance.collection("users").doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
emit(FetchedUserDataSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
}
Future<void> follow(FollowSearchEvent event, Emitter emit) async {
emit(FollowingSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
String? username = sharedPreferences.getString("username");
String? userProfilePhotoUrl =
sharedPreferences.getString("profilePhotoUrl");
var collectionRef = FirebaseFirestore.instance.collection("users");
if (event.fromProfile) {
List followers = state.userData.followers;
followers.add(myUserId);
UserData userData = state.userData.copyWith(followers: followers);
await collectionRef.doc(userData.id).update(userData.toJson());
List following = state.myData.following;
following.add(userData.id);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(FollowedUserSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
} else {
String userId = state.posts[event.index!].userId;
var docSnapshot = await collectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List followers = userData.followers;
followers.add(myUserId);
await collectionRef
.doc(userId)
.update(userData.copyWith(followers: followers).toJson());
List following = state.myData.following;
following.add(userId);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(FollowedUserSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
}
String title = "New Follower";
String imageUrl = "";
String body = "$username follows you";
var userData = await collectionRef
.doc(event.fromProfile
? state.userData.id
: state.posts[event.index!].userId)
.get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService()
.sendNotification(title, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
userProfilePhotoUrl!,
DateTime.now().toString(),
myUserId!,
);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
Future<void> unfollow(UnFollowSearchEvent event, Emitter emit) async {
emit(UnFollowingSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
var sharedPreferences = await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
var collectionRef = FirebaseFirestore.instance.collection("users");
if (event.fromProfile) {
List followers = state.userData.followers;
followers.remove(myUserId);
UserData userData = state.userData.copyWith(followers: followers);
await collectionRef.doc(userData.id).update(userData.toJson());
List following = state.myData.following;
following.remove(userData.id);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(UnFollowedUserSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
} else {
String userId = state.posts[event.index!].userId;
var docSnapshot = await collectionRef.doc(userId).get();
UserData userData = UserData.fromJson(docSnapshot.data()!);
List followers = userData.followers;
followers.remove(myUserId);
await collectionRef
.doc(userId)
.update(userData.copyWith(followers: followers).toJson());
List following = state.myData.following;
following.remove(userId);
UserData myData = state.myData.copyWith(following: following);
await collectionRef.doc(myUserId).update(myData.toJson());
emit(UnFollowedUserSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
}
}
Future<void> deletePost(DeleteSearchProfilePost event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString("userId");
List<Post> posts = List.from(state.userData.posts);
posts.removeAt(event.index);
UserData userData = state.userData.copyWith(posts: posts);
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(DeletedSearchProfilePostState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
}
Future<void> addBookmark(BookmarkSearch event, Emitter emit) async {
List bookmarks = List.from(state.myData.bookmarks);
String postId = state.usersPosts
? state.userData.posts[event.postIndex].id
: state.posts[event.postIndex].id;
if (bookmarks.contains(postId)) {
bookmarks.remove(postId);
} else {
bookmarks.add(postId);
}
UserData myData = state.myData.copyWith(bookmarks: bookmarks);
await FirebaseFirestore.instance
.collection("users")
.doc(myData.id)
.update(myData.toJson());
emit(BookmarkedSearchState(
state.posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
}
Future<void> addComment(AddSearchComment event, Emitter emit) async {
var sharedPreferences = await SharedPreferences.getInstance();
var collectionRef = FirebaseFirestore.instance.collection("users");
List<Comments> existingComments = List.from(event.comments);
String comment = event.comment;
String? myUserId = sharedPreferences.getString('userId');
String? profilePhotoUrl = sharedPreferences.getString('profilePhotoUrl');
String? username = sharedPreferences.getString('username');
String id = const Uuid().v4();
Comments newComment =
Comments(comment, profilePhotoUrl, username, myUserId, id);
existingComments.add(newComment);
if (state.usersPosts) {
List<Post> posts = List.from(state.userData.posts);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingComments);
UserData userData = state.userData.copyWith(posts: posts);
String userId = posts[event.postIndex].userId;
await collectionRef.doc(userId).update(userData.toJson());
emit(AddedCommentSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
} else {
List<Post> posts = List.from(state.posts);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingComments);
String userId = posts[event.postIndex].userId;
String postId = posts[event.postIndex].id;
var documentSnapshot = await collectionRef.doc(userId).get();
var documentData = documentSnapshot.data()!;
for (int i = 0; i < documentData['posts'].length; i++) {
if (documentData['posts'][i]['id'] == postId) {
documentData['posts'][i]['comments'] =
existingComments.map((comment) => comment.toJson());
}
}
await collectionRef.doc(userId).update(documentData);
emit(AddedCommentSearchState(
posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
}
String notificationTitle = "Comment";
String imageUrl = state.usersPosts
? state.userData.posts[event.postIndex].imageUrl
: state.posts[event.postIndex].imageUrl;
String body = "$username commented on your post";
var userData = await collectionRef
.doc(state.usersPosts
? state.userData.posts[event.postIndex].userId
: state.posts[event.postIndex].userId)
.get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService().sendNotification(
notificationTitle, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
profilePhotoUrl!,
DateTime.now().toString(),
myUserId!,
);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
Future<void> deleteComment(DeleteSearchComment event, Emitter emit) async {
List<Comments> existingComments = state.usersPosts
? List.from(state.userData.posts[event.postIndex].comments)
: List.from(state.posts[event.postIndex].comments);
if (state.usersPosts) {
existingComments.removeAt(event.commentIndex);
List<Post> posts = state.userData.posts;
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingComments);
UserData userData = state.userData.copyWith(posts: posts);
String userId = posts[event.postIndex].userId;
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update(userData.toJson());
emit(DeletedCommentSearchState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
} else {
List<Post> posts = List.from(state.posts);
String userId = posts[event.postIndex].userId;
String commentId =
posts[event.postIndex].comments[event.commentIndex].id!;
var collectionRef = FirebaseFirestore.instance.collection("users");
var docSnapshot = await collectionRef.doc(userId).get();
var docData = docSnapshot.data()!;
for (int i = 0; i < docData['posts'].length; i++) {
List comments = docData['posts'][i]['comments'];
for (int j = 0; j < comments.length; j++) {
if (comments[j]['id'] == commentId) {
comments.removeAt(j);
docData['posts'][i]['comments'] = comments;
}
}
}
await collectionRef.doc(userId).update(docData);
existingComments.removeAt(event.commentIndex);
posts[event.postIndex] =
posts[event.postIndex].copyWith(comments: existingComments);
emit(DeletedCommentSearchState(
posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
}
}
Future<void> likePost(SearchLikePostEvent event, Emitter emit) async {
bool liked = false;
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
String? myUserId = sharedPreferences.getString("userId");
String? username = sharedPreferences.getString("username");
String? profilePhotoUrl = sharedPreferences.getString("profilePhotoUrl");
final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final collectionRef = firebaseFirestore.collection("users");
if (event.userPosts) {
List<Post> posts = List.from(state.userData.posts);
List likes = posts[event.postIndex].likes;
if (likes.contains(myUserId)) {
likes.remove(myUserId);
liked = false;
} else {
likes.add(myUserId);
liked = true;
}
posts[event.postIndex] = posts[event.postIndex].copyWith(likes: likes);
UserData userData = state.userData.copyWith(posts: posts);
emit(LikePostState(
state.posts,
state.usersList,
userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
var docRef = collectionRef.doc(event.userId);
var docData = await docRef.get();
Map<String, dynamic> userDocData = docData.data()!;
userDocData["posts"][event.postIndex]["likes"] = likes;
await docRef.update(userDocData);
} else {
List<Post> posts = List.from(state.posts);
List likes = posts[event.postIndex].likes;
if (likes.contains(myUserId)) {
likes.remove(myUserId);
} else {
likes.add(myUserId);
}
posts[event.postIndex] = posts[event.postIndex].copyWith(likes: likes);
emit(LikePostState(
posts,
state.usersList,
state.userData,
state.tabIndex,
state.postsIndex,
state.usersPosts,
state.myData,
state.previousPage));
var docsSnapshot =
await collectionRef.where("id", isNotEqualTo: myUserId).get();
var alldocs = docsSnapshot.docs;
for (int i = 0; i < alldocs.length; i++) {
Map<String, dynamic> documentData = alldocs[i].data();
if (documentData["id"] == event.userId) {
for (int j = 0; j < documentData["posts"].length; j++) {
if (documentData["posts"][j]["id"] == event.postId) {
documentData["posts"][j]["likes"] = likes;
await collectionRef.doc(event.userId).set(documentData);
}
}
}
}
}
if (liked) {
String notificationTitle = "Like";
String imageUrl = event.userPosts
? state.userData.posts[event.postIndex].imageUrl
: state.posts[event.postIndex].imageUrl;
String body = "$username liked your post";
var userData = await collectionRef
.doc(event.userPosts
? state.userData.posts[event.postIndex].userId
: state.posts[event.postIndex].userId)
.get();
List receiverFcmToken =
List.generate(1, (index) => userData.data()!['fcmToken']);
await NotificationService().sendNotification(
notificationTitle, imageUrl, body, receiverFcmToken, false);
var notificationCollectionRef =
FirebaseFirestore.instance.collection("notifications");
var notificationData =
await notificationCollectionRef.doc(userData.data()!['id']).get();
var notifications = [];
if (notificationData.data() == null) {
await notificationCollectionRef
.doc(userData.data()!['id'])
.set({"notifications": [], "new_notifications": false});
} else {
notifications = notificationData.data()!['notifications'];
}
NotificationData newNotification = NotificationData(
const Uuid().v4(),
username!,
body,
imageUrl,
profilePhotoUrl!,
DateTime.now().toString(),
myUserId!,
);
notifications.add(newNotification.toJson());
await notificationCollectionRef
.doc(userData.data()!['id'])
.update({"new_notifications": true, "notifications": notifications});
}
}
Future<void> searchUsers(SearchUsers event, Emitter emit) async {
emit(SearchInitial(
state.posts,
const <UserData>[],
UserData.temp(),
state.tabIndex,
state.postsIndex,
state.usersPosts,
UserData.temp(),
1));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString('userId');
var firebaseCollectionRef = FirebaseFirestore.instance.collection("users");
var result = await firebaseCollectionRef
.orderBy("username")
.startAt([event.text]).get();
var docsList = result.docs;
List<UserData> usersList = [];
for (int i = 0; i < docsList.length; i++) {
usersList.add(UserData.fromJson(docsList[i].data()));
}
var docSnapshot = await firebaseCollectionRef.doc(userId).get();
var docData = docSnapshot.data()!;
UserData myData = UserData.fromJson(docData);
emit(UsersSearched(state.posts, usersList, UserData.temp(), state.tabIndex,
state.postsIndex, state.usersPosts, myData, state.previousPage));
}
Future<void> getPosts(GetPosts event, Emitter emit) async {
emit(SearchInitial(const <Post>[], const <UserData>[],
UserData.temp(),
state.tabIndex,
state.postsIndex,
state.usersPosts,
UserData.temp(),
1));
var sharedPreferences = await SharedPreferences.getInstance();
String? userId = sharedPreferences.getString('userId');
var firestoreCollectionRef = FirebaseFirestore.instance.collection("users");
var result =
await firestoreCollectionRef.where("id", isNotEqualTo: userId).get();
var docsList = result.docs;
List<Post> posts = [];
for (int i = 0; i < docsList.length; i++) {
List postsList = docsList[i].data()['posts'];
for (int j = 0; j < postsList.length; j++) {
posts.add(Post.fromJson(postsList[j]));
}
}
posts.shuffle();
var docSnapshot = await firestoreCollectionRef.doc(userId).get();
var docData = docSnapshot.data()!;
UserData myData = UserData.fromJson(docData);
emit(PostsFetched(
posts,
const <UserData>[],
UserData.temp(),
state.tabIndex,
state.postsIndex,
state.usersPosts,
myData,
state.previousPage));
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages | mirrored_repositories/instagram_clone/lib/pages/splash_screen/splash_screen.dart | import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/main.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/posts/bloc/posts_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:shared_preferences/shared_preferences.dart';
import '../authentication/auth_pages/loginpage.dart';
import '../authentication/bloc/auth_bloc.dart';
import '../homepage/homepage_pages/notification/bloc/notification_bloc.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
bool dataSaved = false;
@override
void initState() {
super.initState();
checkSavedDetails();
}
Future<void> checkSavedDetails() async {
var sharedPreferences = await SharedPreferences.getInstance();
var userId = sharedPreferences.getString('userId');
if (userId != null) {
dataSaved = true;
await FirebaseFirestore.instance
.collection("users")
.doc(userId)
.update({"fcmToken": fcmToken});
}
}
@override
Widget build(BuildContext context) {
return AnimatedSplashScreen.withScreenFunction(
duration: 3000,
centered: true,
splash: Image.asset('assets/images/instagram_logo.jpg'),
backgroundColor: Colors.black,
screenFunction: () async {
if (dataSaved) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => HomepageBloc()..add(GetDetails()),
),
BlocProvider(
create: (context) => ProfileBloc(PageController(
initialPage: 0,
)),
),
BlocProvider(
create: (context) => PostsBloc(),
),
BlocProvider(
create: (context) => SearchBloc(
PageController(
initialPage: 1,
),
FocusNode(),
TextEditingController(),
),
),
BlocProvider(
create: (context) => FeedBloc(PageController(initialPage: 0))
..add(const GetFeed(true)),
),
BlocProvider(
create: (context) => NotificationBloc(),
),
],
child: const HomePage(),
);
} else {
return BlocProvider(
create: (context) => AuthBloc(),
child: const LoginPage(),
);
}
});
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/splash_screen | mirrored_repositories/instagram_clone/lib/pages/splash_screen/splash_cubit/splash_cubit.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:instagram_clone/pages/splash_screen/splash_cubit/splash_state.dart';
class SplashCubit extends Cubit<SplashState> {
SplashCubit() : super(const SplashInitial(false, ""));
// Future<void> checkSavedDetails() async {
// var sharedPreferences = await SharedPreferences.getInstance();
// var userId = sharedPreferences.getString('userId');
// if (userId != null) {
// emit(SplashInitial(true, userId));
// await FirebaseFirestore.instance
// .collection("users")
// .doc(userId)
// .update({"fcmToken": fcmToken});
// }
// }
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/splash_screen | mirrored_repositories/instagram_clone/lib/pages/splash_screen/splash_cubit/splash_state.dart | import 'package:equatable/equatable.dart';
abstract class SplashState extends Equatable {
final bool dataSaved;
final String userId;
const SplashState(this.dataSaved, this.userId);
@override
List<Object?> get props => [dataSaved, userId];
}
class SplashInitial extends SplashState {
const SplashInitial(super.dataSaved, super.userId);
@override
List<Object?> get props => [dataSaved, userId];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/bloc/auth_bloc.dart | 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:instagram_clone/data/user_data.dart';
import 'package:instagram_clone/main.dart';
import 'package:instagram_clone/pages/authentication/auth_pages/signup_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'auth_event.dart';
part 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc() : super(const AuthInitial(true, Gender.other)) {
on<ShowPassword>(
(event, emit) => emit(ViewPassword(event.status, state.gender)));
on<ChangeGender>((event, emit) =>
emit(ChangedGender(state.obscurePassword, event.gender)));
on<RequestSignUpEvent>((event, emit) => signUp(event, emit));
on<RequestLoginEvent>((event, emit) => login(event, emit));
on<ResetPasswordEvent>((event, emit) => resetPassword(event, emit));
}
Future<void> resetPassword(ResetPasswordEvent event, Emitter emit) async {
emit(ResettingPasswordState(state.obscurePassword, state.gender));
String username = event.username;
String email = event.email;
String newPassword = event.password;
var collectionRef = FirebaseFirestore.instance.collection("users");
var docSnapshot = await collectionRef
.where("username", isEqualTo: username)
.where("contact", isEqualTo: email)
.get();
await collectionRef
.doc(docSnapshot.docs[0].id)
.update({"password": newPassword});
emit(PasswordResetSuccessState(state.obscurePassword, state.gender));
}
Future<void> signUp(RequestSignUpEvent event, Emitter emit) async {
emit(LoadingState(state.obscurePassword, state.gender));
try {
UserData data = event.userData.copyWith(fcmToken: fcmToken!);
if (data.contact.isNotEmpty &&
data.name.isNotEmpty &&
data.password.isNotEmpty &&
data.username.isNotEmpty) {
var firebaseStorageRef = FirebaseStorage.instance.ref();
String fileName = "profilePhoto.jpg";
var profilePhotoUrl =
await firebaseStorageRef.child(fileName).getDownloadURL();
UserData userData = data.copyWith(profilePhotoUrl: profilePhotoUrl);
await FirebaseFirestore.instance
.collection('users')
.doc(userData.id)
.set(userData.toJson());
await FirebaseFirestore.instance
.collection("stories")
.doc(userData.id)
.set({
"addedStory": false,
"userId": userData.id,
"previous_stories": [],
"viewed": false,
});
await FirebaseFirestore.instance
.collection("notifications")
.doc(userData.id)
.set({"notifications": [], "new_notifications": false});
emit(SignUpDone(state.obscurePassword, state.gender));
} else {
emit(FillAllDetails(state.obscurePassword, state.gender));
}
} catch (e) {
if (kDebugMode) {
print(e);
}
emit(ErrorState(state.obscurePassword, state.gender));
}
}
Future<void> login(RequestLoginEvent event, Emitter emit) async {
emit(LoadingState(state.obscurePassword, state.gender));
try {
if (event.password.isNotEmpty && event.username.isNotEmpty) {
Query<Map<String, dynamic>> userdata = FirebaseFirestore.instance
.collection('users')
.where('username', isEqualTo: event.username)
.where('password', isEqualTo: event.password);
var snapshotData = await userdata.get();
List docsList = snapshotData.docs;
if (docsList.isNotEmpty) {
UserData userData = UserData.fromJson(docsList.first.data());
if (kDebugMode) {
print(userData.gender);
print(userData.name);
}
var sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString("userId", userData.id);
await sharedPreferences.setString(
"profilePhotoUrl", userData.profilePhotoUrl);
await sharedPreferences.setString("username", userData.username);
await FirebaseFirestore.instance
.collection("users")
.doc(userData.id)
.update({"fcmToken": fcmToken});
if (kDebugMode) {
print("UserId: ${sharedPreferences.getString("userId")}");
}
emit(LoginDone(state.obscurePassword, state.gender));
} else {
emit(UserDataNotAvailable(state.obscurePassword, state.gender));
}
} else {
emit(FillAllDetails(state.obscurePassword, state.gender));
}
} catch (e) {
if (kDebugMode) {
print(e);
}
emit(ErrorState(state.obscurePassword, state.gender));
}
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/bloc/auth_event.dart | part of 'auth_bloc.dart';
abstract class AuthEvent extends Equatable {
const AuthEvent();
@override
List<Object> get props => [];
}
class ShowPassword extends AuthEvent {
final bool status;
const ShowPassword(this.status);
@override
List<Object> get props => [status];
}
class ChangeGender extends AuthEvent {
final Gender gender;
const ChangeGender(this.gender);
@override
List<Object> get props => [gender];
}
class RequestSignUpEvent extends AuthEvent {
final UserData userData;
const RequestSignUpEvent(this.userData);
@override
List<Object> get props => [userData];
}
class RequestLoginEvent extends AuthEvent {
final String username;
final String password;
const RequestLoginEvent(this.username, this.password);
@override
List<Object> get props => [username, password];
}
class ResetPasswordEvent extends AuthEvent {
final String email;
final String username;
final String password;
const ResetPasswordEvent(
{required this.email, required this.username, required this.password});
@override
List<Object> get props => [username, password, email];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/bloc/auth_state.dart | part of 'auth_bloc.dart';
abstract class AuthState extends Equatable {
const AuthState(this.obscurePassword, this.gender);
final bool obscurePassword;
final Gender gender;
@override
List<Object> get props => [obscurePassword, gender];
}
class AuthInitial extends AuthState {
const AuthInitial(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class ViewPassword extends AuthState {
const ViewPassword(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class ChangedGender extends AuthState {
const ChangedGender(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class LoadingState extends AuthState {
const LoadingState(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class SignUpDone extends AuthState {
const SignUpDone(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class LoginDone extends AuthState {
const LoginDone(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class UserDataNotAvailable extends AuthState {
const UserDataNotAvailable(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class FillAllDetails extends AuthState {
const FillAllDetails(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class ErrorState extends AuthState {
const ErrorState(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class ResettingPasswordState extends AuthState {
const ResettingPasswordState(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
class PasswordResetSuccessState extends AuthState {
const PasswordResetSuccessState(super.obscurePassword, super.gender);
@override
List<Object> get props => [obscurePassword, gender];
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/auth_pages/signup_page.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/authentication/bloc/auth_bloc.dart';
import 'package:instagram_clone/widgets/insta_button.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:uuid/uuid.dart';
enum Gender { male, female, other }
class SignupPage extends StatefulWidget {
const SignupPage({super.key});
@override
State<SignupPage> createState() => _SignupPageState();
}
class _SignupPageState extends State<SignupPage> {
final TextEditingController emailController = TextEditingController();
final TextEditingController fullnameController = TextEditingController();
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
Gender value = Gender.other;
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is SignUpDone) {
Navigator.of(context).pop();
} else if (state is ErrorState) {
const InstaSnackbar(
text: "Please try again, something went wrong !!!")
.show(context);
} else if (state is FillAllDetails) {
const InstaSnackbar(text: "Please fill all the details !!!")
.show(context);
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
),
elevation: 0,
backgroundColor: Colors.black,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Align(
alignment: Alignment.center,
child: SizedBox(
height: height * 0.1,
width: width * 0.5,
child: Image.asset('assets/images/instagram.png'),
),
),
SizedBox(
height: height * 0.03,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: emailController,
hintText: "Phone number or email",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: fullnameController,
hintText: "Full name",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: usernameController,
hintText: "Username",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
BlocSelector<AuthBloc, AuthState, bool>(
selector: (state) {
return state.obscurePassword;
},
builder: (context, state) {
return InstaTextField(
enabled: true,
editProfileTextfield: false,
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: passwordController,
hintText: "Password",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: state,
forPassword: true,
suffixIcon: state
? const Icon(
Icons.visibility,
color: Colors.white,
)
: const Icon(
Icons.visibility_off,
color: Colors.white,
),
suffixIconCallback: () {
context.read<AuthBloc>().add(ShowPassword(!state));
},
onChange: (value) {},
);
},
),
SizedBox(
height: height * 0.03,
),
Row(
children: [
const InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Gender"),
SizedBox(
width: width * 0.1,
),
Row(
children: [
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return Radio(
fillColor: MaterialStateColor.resolveWith(
(states) => state.gender == Gender.male
? Colors.white
: profilePhotoBorder),
value: Gender.male,
groupValue: state.gender,
onChanged: (val) {
// print(val);
context
.read<AuthBloc>()
.add(ChangeGender(val!));
});
},
),
const InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Male")
],
),
Row(
children: [
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return Radio(
fillColor: MaterialStateColor.resolveWith(
(states) => state.gender == Gender.female
? Colors.white
: profilePhotoBorder),
value: Gender.female,
groupValue: state.gender,
onChanged: (val) {
// print(val);
context
.read<AuthBloc>()
.add(ChangeGender(val!));
});
},
),
const InstaText(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
text: "Female"),
],
)
],
),
SizedBox(
height: height * 0.03,
),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is LoadingState) {
return SizedBox(
height: height * 0.065,
child: const Center(
child: CircularProgressIndicator(
strokeWidth: 1,
color: Colors.white,
),
),
);
} else {
return InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.065,
buttonColor: instablue,
onPressed: () async {
String uId = const Uuid().v4();
String name = fullnameController.text;
String username = usernameController.text;
String contact = emailController.text;
String password = passwordController.text;
int gender =
context.read<AuthBloc>().state.gender == Gender.male
? 1
: 0;
UserData userData = UserData(
uId,
name,
username,
contact,
password,
gender,
"",
"",
[],
[],
[],
[],
"",
false,
[],
false,
"");
context
.read<AuthBloc>()
.add(RequestSignUpEvent(userData));
},
text: "Sign up",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700,
);
}
},
),
SizedBox(
height: height * 0.05,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InstaText(
fontSize: 14,
color: Colors.white.withOpacity(0.6),
fontWeight: FontWeight.normal,
text: "Already have an account? "),
InkWell(
onTap: () {
Navigator.of(context).pop();
},
child: InstaText(
fontSize: 14,
color: instablue,
fontWeight: FontWeight.normal,
text: "Log in"),
)
],
)
]),
),
),
),
);
}
@override
void dispose() {
emailController.dispose();
fullnameController.dispose();
usernameController.dispose();
passwordController.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/auth_pages/reset_password_page.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/bloc/auth_bloc.dart';
import 'package:instagram_clone/widgets/insta_snackbar.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import '../../../widgets/insta_button.dart';
class ResetPasswordPage extends StatefulWidget {
const ResetPasswordPage({super.key});
@override
State<ResetPasswordPage> createState() => _ResetPasswordPageState();
}
class _ResetPasswordPageState extends State<ResetPasswordPage> {
final TextEditingController userNameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final TextEditingController emailController = TextEditingController();
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is PasswordResetSuccessState) {
const InstaSnackbar(text: "Password Reset Successfull").show(context);
Navigator.of(context).pop();
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
),
elevation: 0,
backgroundColor: Colors.black,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: height * 0.1,
),
SizedBox(
height: height * 0.1,
width: width * 0.5,
child: Image.asset('assets/images/instagram.png')),
SizedBox(
height: height * 0.05,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: emailController,
hintText: "Phone number or email",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: userNameController,
hintText: "Username",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: true,
suffixIcon: state.obscurePassword
? const Icon(
Icons.visibility,
color: Colors.white,
)
: const Icon(
Icons.visibility_off,
color: Colors.white,
),
suffixIconCallback: () {
context
.read<AuthBloc>()
.add(ShowPassword(!state.obscurePassword));
},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: passwordController,
hintText: "New Password",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: state.obscurePassword,
onChange: (value) {},
);
},
),
SizedBox(
height: height * 0.02,
),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is ResettingPasswordState) {
return SizedBox(
height: height * 0.065,
child: const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
),
);
} else {
return InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.065,
buttonColor: instablue,
onPressed: () {
String username = userNameController.text;
String password = passwordController.text;
String email = emailController.text;
context.read<AuthBloc>().add(ResetPasswordEvent(
username: username,
password: password,
email: email));
},
text: "Reset Password",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700);
}
},
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib/pages/authentication | mirrored_repositories/instagram_clone/lib/pages/authentication/auth_pages/loginpage.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/reset_password_page.dart';
import 'package:instagram_clone/pages/authentication/bloc/auth_bloc.dart';
import 'package:instagram_clone/pages/homepage/bloc/homepage_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage.dart';
import 'package:instagram_clone/pages/authentication/auth_pages/signup_page.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/feed/bloc/feed_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/notification/bloc/notification_bloc.dart';
import 'package:instagram_clone/pages/homepage/homepage_pages/posts/bloc/posts_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/insta_button.dart';
import 'package:instagram_clone/widgets/insta_snackbar.dart';
import 'package:instagram_clone/widgets/insta_textfield.dart';
import 'package:instagram_clone/widgets/instatext.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController userNameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is LoginDone) {
const InstaSnackbar(text: "Login Successfull !!!").show(context);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => HomepageBloc()..add(GetDetails()),
),
BlocProvider(
create: (context) => ProfileBloc(PageController(
initialPage: 0,
)),
),
BlocProvider(
create: (context) => PostsBloc(),
),
BlocProvider(
create: (context) => SearchBloc(
PageController(
initialPage: 1,
),
FocusNode(),
TextEditingController(),
),
),
BlocProvider(
create: (context) =>
FeedBloc(PageController(initialPage: 0))
..add(const GetFeed(true)),
),
BlocProvider(
create: (context) => NotificationBloc(),
)
],
child: const HomePage(),
)));
} else if (state is UserDataNotAvailable) {
const InstaSnackbar(text: "Incorrect username or password")
.show(context);
} else if (state is FillAllDetails) {
const InstaSnackbar(text: "Please fill all the details !!!")
.show(context);
} else if (state is ErrorState) {
const InstaSnackbar(text: "Something went wrong !!!").show(context);
}
},
child: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.black,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: height * 0.1,
),
SizedBox(
height: height * 0.1,
width: width * 0.5,
child: Image.asset('assets/images/instagram.png')),
SizedBox(
height: height * 0.05,
),
InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: false,
suffixIcon: null,
suffixIconCallback: () {},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: userNameController,
hintText: "Username",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: false,
onChange: (value) {},
),
SizedBox(
height: height * 0.02,
),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return InstaTextField(
enabled: true,
editProfileTextfield: false,
forPassword: true,
suffixIcon: state.obscurePassword
? const Icon(
Icons.visibility,
color: Colors.white,
)
: const Icon(
Icons.visibility_off,
color: Colors.white,
),
suffixIconCallback: () {
context
.read<AuthBloc>()
.add(ShowPassword(!state.obscurePassword));
},
backgroundColor: textFieldBackgroundColor,
borderRadius: 5,
icon: null,
controller: passwordController,
hintText: "Password",
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.normal,
hintColor: Colors.white.withOpacity(0.6),
obscureText: state.obscurePassword,
onChange: (value) {},
);
},
),
SizedBox(
height: height * 0.02,
),
Align(
alignment: Alignment.centerRight,
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => BlocProvider(
create: (context) => AuthBloc(),
child: const ResetPasswordPage())));
},
child: InstaText(
fontSize: 12,
color: instablue,
fontWeight: FontWeight.w500,
text: "Forgot password?"),
),
),
SizedBox(
height: height * 0.035,
),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is LoadingState) {
return SizedBox(
height: height * 0.065,
child: const Center(
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 1,
),
),
);
} else {
return InstaButton(
borderWidth: 1,
width: double.infinity,
postButton: false,
height: height * 0.065,
buttonColor: instablue,
onPressed: () {
String username = userNameController.text;
String password = passwordController.text;
context
.read<AuthBloc>()
.add(RequestLoginEvent(username, password));
},
text: "Log in",
fontSize: 14,
textColor: Colors.white,
fontWeight: FontWeight.w700);
}
},
),
SizedBox(
height: height * 0.05,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InstaText(
fontSize: 14,
color: Colors.white.withOpacity(0.6),
fontWeight: FontWeight.normal,
text: "Dont have an account? "),
InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: ((context) => MultiBlocProvider(
providers: [
BlocProvider(
create: (create) => AuthBloc(),
),
],
child: const SignupPage(),
))));
},
child: InstaText(
fontSize: 14,
color: instablue,
fontWeight: FontWeight.normal,
text: "Sign up."),
)
],
)
],
),
),
),
),
);
}
@override
void dispose() {
userNameController.dispose();
passwordController.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/utility/firebase_messaging_service.dart | import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:instagram_clone/main.dart';
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
if (kDebugMode) {
print("Handling a background message: ${message.data}");
}
}
class FirebaseMessagingService {
var firebaseMessaging = FirebaseMessaging.instance;
Future<void> initNotifications() async {
await firebaseMessaging.requestPermission();
fcmToken = await firebaseMessaging.getToken();
if (kDebugMode) {
print("fcmToken $fcmToken");
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (kDebugMode) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
}
if (message.notification != null) {
if (kDebugMode) {
print(
'Message also contained a notification: ${message.notification!.title}');
}
}
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/utility/notification_service.dart | import 'package:dio/dio.dart';
import 'api_keys.dart';
class NotificationService {
var dio = Dio();
String url = "https://fcm.googleapis.com/fcm/send";
String serverKey = yourServerKey;
Future<void> sendNotification(String title, String imageUrl, String body,
List receiverFcmToken, bool isMulticast) async {
await dio.post(
url,
options: Options(
headers: {
"Content-Type": "application/json",
"Authorization": "key=$serverKey"
},
),
data: isMulticast
? {
"notification": {
"title": title,
"image": imageUrl,
"body": body,
},
"registration_ids": receiverFcmToken,
}
: {
"notification": {
"title": title,
"image": imageUrl,
"body": body,
},
"to": receiverFcmToken[0],
},
);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/homepage_data.dart | class HomePageData {
final String url;
const HomePageData(this.url);
factory HomePageData.fromJson(Map<String, dynamic> json) {
return HomePageData(json['url']);
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/posts_data.dart | import 'package:instagram_clone/data/comment_data.dart';
class Post {
String id;
String userProfilePhotoUrl;
String username;
String imageUrl;
List likes;
List<Comments> comments;
String caption;
String userId;
Post({
required this.id,
required this.username,
required this.imageUrl,
required this.likes,
required this.comments,
required this.caption,
required this.userId,
required this.userProfilePhotoUrl,
});
Post copyWith({
String? id,
String? username,
String? imageUrl,
List? likes,
List<Comments>? comments,
String? caption,
String? userId,
String? userProfilePhotoUrl,
}) {
return Post(
id: id ?? this.id,
username: username ?? this.username,
imageUrl: imageUrl ?? this.imageUrl,
likes: likes ?? this.likes,
comments: comments ?? this.comments,
caption: caption ?? this.caption,
userId: userId ?? this.userId,
userProfilePhotoUrl: userProfilePhotoUrl ?? this.userProfilePhotoUrl,
);
}
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
username: json["username"],
imageUrl: json["imageUrl"],
likes: json["likes"],
comments: List.from(json["comments"].map((comment) => Comments(
comment["comment"],
comment['profilePhotoUrl'],
comment['username'],
comment['userId'],
comment['id'],
))),
caption: json["caption"],
userId: json['userId'],
userProfilePhotoUrl: json['userProfilePhotoUrl'],
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"username": username,
"imageUrl": imageUrl,
"likes": likes,
"comments": comments.map((e) => e.toJson()),
"caption": caption,
"userId": userId,
"userProfilePhotoUrl": userProfilePhotoUrl,
};
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/stories.dart | class StoryData {
final Story story;
final bool viewed;
StoryData({
required this.story,
required this.viewed,
});
StoryData copyWith({Story? story, bool? viewed}) {
return StoryData(
story: story ?? this.story,
viewed: viewed ?? this.viewed,
);
}
}
class Story {
final String id;
final String userProfilePhotoUrl;
final String username;
final String imageUrl;
final String caption;
final String userId;
final String date;
Story({
required this.id,
required this.userProfilePhotoUrl,
required this.username,
required this.imageUrl,
required this.caption,
required this.userId,
required this.date,
});
factory Story.temp() {
return Story(
id: "id",
userProfilePhotoUrl: "userProfilePhotoUrl",
username: "username",
imageUrl: "imageUrl",
caption: "caption",
userId: "userId",
date: "date");
}
factory Story.fromJson(Map<String, dynamic> json) {
return Story(
id: json["id"],
userProfilePhotoUrl: json["userProfilePhotoUrl"],
username: json["username"],
imageUrl: json["imageUrl"],
caption: json["caption"],
userId: json["userId"],
date: json["date"],
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"userProfilePhotoUrl": userProfilePhotoUrl,
"username": username,
"imageUrl": imageUrl,
"caption": caption,
"userId": userId,
"date": date,
};
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/user_data.dart | import 'package:instagram_clone/data/comment_data.dart';
import 'package:instagram_clone/data/posts_data.dart';
import 'package:instagram_clone/data/stories.dart';
class UserData {
final String id;
final String name;
final String username;
final String contact;
final String password;
final int gender;
final String bio;
final String tagline;
final List<Story> stories;
final List<Post> posts;
final List followers;
final List following;
final String profilePhotoUrl;
final bool private;
final List bookmarks;
final bool addedStory;
final String fcmToken;
UserData(
this.id,
this.name,
this.username,
this.contact,
this.password,
this.gender,
this.bio,
this.tagline,
this.posts,
this.stories,
this.followers,
this.following,
this.profilePhotoUrl,
this.private,
this.bookmarks,
this.addedStory,
this.fcmToken,
);
factory UserData.temp() {
return UserData("id", "name", "username", "contact", "password", 1, "bio",
"tagline", [], [], [], [], "", false, [], false, "");
}
UserData copyWith({
String? id,
String? name,
String? username,
String? contact,
String? password,
int? gender,
String? bio,
String? tagline,
List<Post>? posts,
List<Story>? stories,
List? followers,
List? following,
String? profilePhotoUrl,
bool? private,
List? bookmarks,
bool? addedStory,
String? fcmToken,
}) {
return UserData(
id ?? this.id,
name ?? this.name,
username ?? this.username,
contact ?? this.contact,
password ?? this.password,
gender ?? this.gender,
bio ?? this.bio,
tagline ?? this.tagline,
posts ?? this.posts,
stories ?? this.stories,
followers ?? this.followers,
following ?? this.following,
profilePhotoUrl ?? this.profilePhotoUrl,
private ?? this.private,
bookmarks ?? this.bookmarks,
addedStory ?? this.addedStory,
fcmToken ?? this.fcmToken,
);
}
factory UserData.fromJson(Map<String, dynamic> json) {
return UserData(
json['id'],
json['name'],
json['username'],
json['contact'],
json['password'],
json['gender'],
json['bio'],
json['tagline'],
List<Post>.from(
json['posts'].map(
(post) => Post(
id: post['id'],
username: post['username'],
imageUrl: post['imageUrl'],
likes: post['likes'],
comments: List.from(post["comments"].map((comment) => Comments(
comment["comment"],
comment['profilePhotoUrl'],
comment['username'],
comment["userId"],
comment["id"],
))),
caption: post['caption'],
userId: post['userId'],
userProfilePhotoUrl: post['userProfilePhotoUrl']),
),
),
List.from(
json['stories'].map(
(story) => Story(
id: story['id'],
userProfilePhotoUrl: story['userProfilePhotoUrl'],
username: story['username'],
imageUrl: story['imageUrl'],
caption: story['caption'],
userId: story['userId'],
date: story['date'],
),
),
),
json['followers'],
json['following'],
json['profilePhotoUrl'],
json['private'],
json['bookmarks'],
json['addedStory'],
json['fcmToken'],
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"name": name,
"username": username,
"contact": contact,
"password": password,
"gender": gender,
"bio": bio,
"tagline": tagline,
"stories": stories.map((e) => e.toJson()),
"posts": posts.map((e) => e.toJson()),
"followers": followers,
"following": following,
"profilePhotoUrl": profilePhotoUrl,
"private": private,
"bookmarks": bookmarks,
"addedStory": addedStory,
"fcmToken": fcmToken,
};
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/comment_data.dart | class Comments {
String? comment;
String? username;
String? profilePhotoUrl;
String? userId;
String? id;
Comments(
this.comment, this.profilePhotoUrl, this.username, this.userId, this.id);
Comments.fromJson(Map<String, dynamic> json) {
comment = json['comment'];
profilePhotoUrl = json['profilePhotoUrl'];
username = json['username'];
userId = json['userId'];
id = json['id'];
}
Map<String, dynamic> toJson() {
return {
"comment": comment,
"username": username,
"profilePhotoUrl": profilePhotoUrl,
"userId": userId,
"id": id,
};
}
}
| 0 |
mirrored_repositories/instagram_clone/lib | mirrored_repositories/instagram_clone/lib/data/notification_data.dart | class NotificationData {
String id;
String username;
String message;
String imageUrl;
String dateTime;
String userProfilePhoto;
String senderUserId;
NotificationData(this.id, this.username, this.message, this.imageUrl,
this.userProfilePhoto, this.dateTime, this.senderUserId);
factory NotificationData.fromJson(Map<String, dynamic> json) {
return NotificationData(
json['id'],
json['username'],
json['message'],
json['imageUrl'],
json['userProfilePhoto'],
json['dateTime'],
json['senderUserId']);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"username": username,
"message": message,
"imageUrl": imageUrl,
"userProfilePhoto": userProfilePhoto,
"dateTime": dateTime,
"senderUserId": senderUserId,
};
}
}
| 0 |
mirrored_repositories/instagram_clone | mirrored_repositories/instagram_clone/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:instagram_clone/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Mobile | mirrored_repositories/Mobile/lib/main.dart | import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
var tittlestyle = theme.textTheme.headline2?.copyWith(
fontWeight: FontWeight.w800,
);
var bodystyle = theme.textTheme.bodyText1?.copyWith(
fontWeight: FontWeight.w800,
);
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: Column(
children: [
Text('Naruto', style: tittlestyle!! ,),
Padding(
//padging o espaçamento e da margem para dentro e margin da margem para fora
padding: const EdgeInsets.all(12),
child: Image.asset('lib/assets/images/naruto.jpeg'),
),
Container( margin: const EdgeInsets.only(
top: 18,
bottom: 18,
),
child: Text('Ramem é o muito famoso do anime Naruto, onde o protagonista é um tremendo fã! ', style: bodystyle,),
),
Column(
children: const [
Text('Muito gosotoso!'),
Text('É saboroso!'),
Text('Nutritivo!'),
Text('Me come!'),
],
)
],
),
);
}
}
class Aplicacao extends StatelessWidget {
const Aplicacao({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Naruto',
theme: ThemeData(
primarySwatch: Colors.pink,
),
home: const HomePage(),
);
}
}
void main() => runApp(const Aplicacao()); | 0 |
mirrored_repositories/Mobile | mirrored_repositories/Mobile/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_application_1/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/amazox_prime | mirrored_repositories/amazox_prime/lib/app.dart | export 'package:amazon_prime/src/app/cofix.dart';
export 'package:card/shopping_card.dart';
export 'package:core/core.dart';
export 'package:core/di/firebase_options.dart';
export 'package:core_ui/core_ui.dart';
export 'package:flutter/material.dart';
export 'package:home/src/home.dart';
export 'package:navigation/navigation.dart';
export 'package:order/order.dart';
export 'package:product_details/product_details.dart';
export 'package:settings/settings.dart';
| 0 |
mirrored_repositories/amazox_prime | mirrored_repositories/amazox_prime/lib/main.dart | import 'package:amazon_prime/app.dart';
import 'package:data/data.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await initAppModule();
await initDataLayer();
initNavigation();
initSettingsBloc();
await _initHive();
runApp(Application());
}
Future<void> _initHive() async {
await Hive.initFlutter();
await getIt<LocaleDataSource>().initBox();
await getIt<UserLocale>().initBox();
}
| 0 |
mirrored_repositories/amazox_prime/lib/src | mirrored_repositories/amazox_prime/lib/src/app/cofix.dart | import 'package:amazon_prime/app.dart';
class Application extends StatelessWidget {
Application({super.key});
final AppRouter appRouter = getIt.get<AppRouter>();
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: <BlocProvider>[
BlocProvider<OrderBloc>(
create: (BuildContext context) =>
OrderBloc(getAllUserOrders: getIt<GetAllUserOrdersUseCase>()),
),
BlocProvider<ThemeCubit>(
create: (BuildContext context) => getIt<ThemeCubit>(),
),
BlocProvider<CartBloc>(
create: (BuildContext context) => CartBloc(
saveOrderRemoteUseCase: getIt<SaveOrderRemoteUseCase>(),
saveUserOrderUseCase: getIt<SaveUserOrderUseCase>(),
addCartItemUseCase: getIt<AddCartItemUseCase>(),
getAllCartItemsUseCase: getIt<GetAllCartItemsUseCase>(),
removeCartItemUseCase: getIt<RemoveCartItemUseCase>(),
removeAllCartItemsUseCase: getIt<RemoveAllCartItemsUseCase>(),
)..add(LoadCart()),
),
BlocProvider<SettingsBloc>(
create: (BuildContext context) => SettingsBloc(
getCurrentUserUseCase: getIt<GetCurrentUserUseCase>(),
changeUserAvatarUserCase: getIt<ChangeUserAvatarUserCase>(),
imagePicker: getIt<ImagePicker>(),
appRouter: getIt<AppRouter>(),
logOutUseCase: getIt<LogOutUseCase>(),
urlLauncher: getIt<UrlLauncher>(),
getFontSizeUseCase: getIt<GetFontSizeUseCase>(),
saveFontSizeUseCase: getIt<SaveFontSizeUseCase>(),
)..add(
GetFontSizeEvent(),
),
),
BlocProvider<OnBoardingCubit>(
create: (BuildContext context) => OnBoardingCubit(
cacheFirstTimer: getIt<CacheFirstTimerUseCase>(),
checkIfUserIsFirstTimer: getIt<CheckIfUserIsFirstTimerUseCase>(),
),
child: Provider(
create: (BuildContext context) => ChangeNotifierProvider(
create: (BuildContext context) => UserProvider(),
),
),
),
BlocProvider<AuthBloc>(
create: (BuildContext context) => AuthBloc(
signInWithGoogleUseCase: getIt<SignInWithGoogleUseCase>(),
autoRouter: getIt<AppRouter>(),
signInUseCase: getIt<SignInUseCase>(),
signUpUseCase: getIt<SignUpUseCase>(),
forgotPasswordUseCase: getIt<ForgotPasswordUseCase>(),
),
),
],
child: BlocBuilder<ThemeCubit, ThemeState>(
builder: _buildWithTheme,
),
);
}
Widget _buildWithTheme(
BuildContext context,
ThemeState state,
) {
return MaterialApp.router(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: context.mediaQuery.copyWith(
textScaleFactor:
context.watch<SettingsBloc>().state.fontSize?.fontSize,
),
child: child ?? const SizedBox.shrink(),
);
},
debugShowCheckedModeBanner: false,
theme: getIt<ThemeCubit>().isDark
? DarkTheme.instance.darkTheme
: LightTheme.instance.lightTheme,
routerDelegate: AutoRouterDelegate(appRouter),
routeInformationParser: appRouter.defaultRouteParser(),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/test | mirrored_repositories/amazox_prime/test/lib/test.dart | library test;
export 'package:auth/auth.dart';
export 'package:bloc_test/bloc_test.dart';
export 'package:card/shopping_card.dart';
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:data/data.dart';
export 'package:domain/domain.dart';
export 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
export 'package:google_sign_in_mocks/google_sign_in_mocks.dart';
export 'package:home/src/home.dart';
export 'package:json_annotation/json_annotation.dart';
export 'package:mocktail/mocktail.dart';
export 'package:onboarding/onboarding.dart';
export 'package:settings/settings.dart';
export 'package:testing/widget/core_ui/test_wrapper_widget.dart';
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/features | mirrored_repositories/amazox_prime/test/lib/unit/features/auth/auth_bloc_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockSignInUseCase extends Mock implements SignInUseCase {}
class MockSignInWithGoogleUseCase extends Mock
implements SignInWithGoogleUseCase {}
class MockSignUpUseCase extends Mock implements SignUpUseCase {}
class MockAppRouter extends Mock implements AppRouter {}
class MockForgotPasswordUseCase extends Mock implements ForgotPasswordUseCase {}
void main() {
late SignInUseCase signInUseCase;
late SignInWithGoogleUseCase signInWithGoogleUseCase;
late SignUpUseCase signUpUseCase;
late ForgotPasswordUseCase forgotPasswordUseCase;
late AppRouter appRouter;
late AuthBloc authBloc;
UserEntity user = UserEntity.empty();
const String testPassword = 'password';
const String testEmail = 'email';
const String testFullName = 'fullName';
const SignInParams signInParams = SignInParams(
email: testEmail,
password: testPassword,
);
const SignUpParams signUpParams = SignUpParams(
email: testEmail,
password: testPassword,
fullName: testFullName,
);
registerFallbackValue(signInParams);
registerFallbackValue(signUpParams);
setUp(
() {
signInUseCase = MockSignInUseCase();
signInWithGoogleUseCase = MockSignInWithGoogleUseCase();
signUpUseCase = MockSignUpUseCase();
forgotPasswordUseCase = MockForgotPasswordUseCase();
appRouter = MockAppRouter();
authBloc = AuthBloc(
signInWithGoogleUseCase: signInWithGoogleUseCase,
signInUseCase: signInUseCase,
signUpUseCase: signUpUseCase,
forgotPasswordUseCase: forgotPasswordUseCase,
autoRouter: appRouter,
);
},
);
group(
'Auth bloc test',
() {
test(
'initial state should be AuthInitialState ',
() async {
expect(
authBloc.state,
const AuthInitialState(),
);
},
);
},
);
blocTest<AuthBloc, AuthState>(
'should emit [AuthLoadingState] when SignInEvent is added.',
build: () {
when<Future<Either<Failure, UserEntity>>>(
() => signInUseCase(any<SignInParams>()),
).thenAnswer(
(Invocation invocation) async {
return Right<Failure, UserEntity>(user);
},
);
return authBloc;
},
act: (AuthBloc bloc) => bloc.add(
SignInEvent(
email: signInParams.email,
password: signInParams.password,
),
),
expect: () => <AuthState>[
const AuthLoadingState(),
SignedInState(user: user),
],
);
blocTest<AuthBloc, AuthState>(
'should emit [AuthLoadingState] when SingUpEvent is added.',
build: () {
when<Future<Either<Failure, void>>>(
() => signUpUseCase(any<SignUpParams>()),
).thenAnswer(
(Invocation invocation) async {
return const Right<Failure, void>(null);
},
);
return authBloc;
},
act: (AuthBloc bloc) => bloc.add(
SignUpEvent(
name: testFullName,
email: signInParams.email,
password: signInParams.password,
),
),
expect: () => const <AuthState>[
AuthLoadingState(),
SignedUpState(),
],
);
tearDown(() => authBloc.close());
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/data/data_provider | mirrored_repositories/amazox_prime/test/lib/unit/data/data_provider/auth/auth_remote_data_source_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockFirebaseAuth extends Mock implements FirebaseAuth {}
class MockUser extends Mock implements User {
String _uid = 'Test uid';
@override
String get uid => _uid;
set uid(String value) {
if (_uid != value) _uid = value;
}
}
class MockUserCredential extends Mock implements UserCredential {
MockUserCredential([User? user]) : _user = user;
User? _user;
@override
User? get user => _user;
set user(User? value) {
if (_user != value) _user = value;
}
}
class MockAuthCredential extends Mock implements AuthCredential {}
void main() {
late MockFirebaseAuth authClient;
late FakeFirebaseFirestore cloudStoreClient;
late AuthRemoteDataSource dataSource;
late MockUser mockUser;
late DocumentReference<Map<String, dynamic>> docReference;
late MockUserCredential userCredential;
late MockGoogleSignIn googleSignIn;
UserModel tUser = UserModel.empty();
setUpAll(
() async {
cloudStoreClient = FakeFirebaseFirestore();
docReference = await cloudStoreClient.collection('users').add(
tUser.toMap(),
);
await cloudStoreClient.collection('users').doc(docReference.id).update(
<Object, Object>{'uid': docReference.id},
);
mockUser = MockUser()..uid = docReference.id;
userCredential = MockUserCredential(mockUser);
authClient = MockFirebaseAuth();
googleSignIn = MockGoogleSignIn();
when<User?>(() => authClient.currentUser).thenReturn(mockUser);
dataSource = AuthRemoteDataSourceImpl(
googleSignIn: googleSignIn,
authClient: authClient,
cloudStoreClient: cloudStoreClient,
);
},
);
const String userPassword = 'Test password';
const String userFullName = 'Test full name';
const String userEmail = 'Test email';
final FirebaseAuthException firebaseException = FirebaseAuthException(
code: 'user-not-found',
message: 'There is no user record corresponding to this identifier. '
'The user may have been deleted.',
);
group(
'forgotPassword',
() {
test(
'should complete successfully when no [Exception] is thrown',
() async {
when<Future<void>>(
() => authClient.sendPasswordResetEmail(
email: any<String>(named: 'email'),
),
).thenAnswer((Invocation _) async => Future<void>.value());
final Future<void> call = dataSource.forgotPassword(userEmail);
expect(call, completes);
verify<Future<void>>(() {
return authClient.sendPasswordResetEmail(email: userEmail);
}).called(1);
verifyNoMoreInteractions(authClient);
},
);
test(
'should throw [ServerException] when [FirebaseAuthException] is thrown',
() async {
when<Future<void>>(
() {
return authClient.sendPasswordResetEmail(
email: any(named: 'email'),
);
},
).thenThrow(firebaseException);
final Future<void> Function(String email) call =
dataSource.forgotPassword;
expect(() => call(userEmail), throwsA(isA<ServerException>()));
verify<Future<void>>(() {
return authClient.sendPasswordResetEmail(email: userEmail);
}).called(1);
verifyNoMoreInteractions(authClient);
},
);
},
);
group('signIn', () {
test(
'should return [LocalUserModel] when no [Exception] is thrown',
() async {
when<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: any<String>(named: 'email'),
password: any<String>(named: 'password'),
);
},
).thenAnswer((Invocation _) async => userCredential);
final UserModel result = await dataSource.signIn(
email: userEmail,
password: userPassword,
);
expect(result.uid, userCredential.user!.uid);
expect(result.email, tUser.email);
verify<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
},
).called(1);
verifyNoMoreInteractions(authClient);
},
);
test(
'should throw [ServerException] when user is null after signing in',
() async {
final MockUserCredential userCred = MockUserCredential();
when<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: any<String>(named: 'email'),
password: any<String>(named: 'password'),
);
},
).thenAnswer((Invocation _) async => userCred);
final Future<UserModel> Function({
required String email,
required String password,
}) call = dataSource.signIn;
expect(
() {
return call(
email: userEmail,
password: userPassword,
);
},
throwsA(isA<ServerException>()),
);
verify<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
},
).called(1);
verifyNoMoreInteractions(authClient);
},
);
test(
'should throw [ServerException] when [FirebaseAuthException] is thrown',
() async {
when<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: any<String>(named: 'email'),
password: any<String>(named: 'password'),
);
},
).thenThrow(firebaseException);
final Future<UserModel> Function({
required String email,
required String password,
}) call = dataSource.signIn;
expect(
() {
return call(
email: userEmail,
password: userPassword,
);
},
throwsA(isA<ServerException>()),
);
verify<Future<UserCredential>>(
() {
return authClient.signInWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
},
).called(1);
verifyNoMoreInteractions(authClient);
},
);
});
group(
'signUp',
() {
test(
'should complete successfully when no [Exception] is thrown',
() async {
when<Future<UserCredential>>(
() {
return authClient.createUserWithEmailAndPassword(
email: any<String>(named: 'email'),
password: any<String>(named: 'password'),
);
},
).thenAnswer((Invocation _) async => MockUserCredential());
final Future<void> call = dataSource.signUp(
email: userEmail,
password: userPassword,
fullName: userFullName,
);
expect(
call,
completes,
);
verify<Future<UserCredential>>(
() {
return authClient.createUserWithEmailAndPassword(
email: userEmail,
password: userPassword,
);
},
).called(1);
test(
'should throw [ServerException] when [FirebaseAuthException] is thrown',
() async {
when<Future<UserCredential>>(
() {
return authClient.createUserWithEmailAndPassword(
email: any<String>(named: 'email'),
password: any<String>(named: 'password'),
);
},
).thenThrow(firebaseException);
final Future<void> Function({
required String email,
required String fullName,
required String password,
}) call = dataSource.signUp;
expect(
() {
return call(
email: userEmail,
password: userPassword,
fullName: userFullName,
);
},
throwsA(isA<ServerException>()),
);
verify<Future<UserCredential>>(
() => authClient.createUserWithEmailAndPassword(
email: userEmail,
password: userPassword,
),
).called(1);
},
);
},
);
},
);
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase | mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase/auth/sign_up_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockAuthRepository extends Mock implements AuthRepository {}
void main() {
late SignUpUseCase signUpUseCase;
late AuthRepository authRepository;
setUp(
() {
authRepository = MockAuthRepository();
signUpUseCase = SignUpUseCase(authRepository);
},
);
const SignUpParams params = SignUpParams(
email: '[email protected]',
fullName: 'Ali',
password: '12345',
);
test(
'should call the [AuthRepository.signUp]',
() async {
//arrange
when(
() => authRepository.signUp(
email: any(named: 'email'),
fullName: any(named: 'fullName'),
password: any(named: 'password'),
),
).thenAnswer((_) async => const Right<Failure, void>(null));
//act
final Either<Failure, void> result = await signUpUseCase(params);
// assert
expect(
result,
equals(
const Right<Failure, void>(null),
),
);
verify(
() => authRepository.signUp(
email: params.email,
fullName: params.fullName,
password: params.password,
),
).called(1);
verifyNoMoreInteractions(authRepository);
},
);
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase | mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase/auth/sign_in_with_google_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockAuthRepository extends Mock implements AuthRepository {}
void main() {
late SignInWithGoogleUseCase signInWithGoogleUseCase;
late AuthRepository authRepository;
setUp(
() {
authRepository = MockAuthRepository();
signInWithGoogleUseCase = SignInWithGoogleUseCase(authRepository);
},
);
SignInWithGoogleParams params = const SignInWithGoogleParams();
UserEntity user = UserEntity(
registrationDate: Timestamp.now(),
fullName: '',
bio: '',
uid: '1',
emailIsVerified: false,
image: 'sss',
email: '[email protected]',
username: 'ali',
);
test('should call the [AuthRepository.singIn()]', () async {
//arrange
when(
() => authRepository.signInWithGoogle(),
).thenAnswer((_) async => Right<Failure, UserEntity>(user));
//act
final Either<Failure, void> result = await signInWithGoogleUseCase(params);
// assert
expect(
result,
equals(
Right<Failure, UserEntity>(user),
),
);
verify(
() => authRepository.signInWithGoogle(),
).called(1);
verifyNoMoreInteractions(authRepository);
});
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase | mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase/auth/sign_in_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockAuthRepository extends Mock implements AuthRepository {}
void main() {
late SignInUseCase signInUseCase;
late AuthRepository authRepository;
setUp(
() {
authRepository = MockAuthRepository();
signInUseCase = SignInUseCase(authRepository);
},
);
SignInParams params = const SignInParams(
email: '[email protected]',
password: '123455',
);
UserEntity user = UserEntity(
registrationDate: Timestamp.now(),
fullName: '',
bio: '',
uid: '1',
emailIsVerified: false,
image: 'sss',
email: '[email protected]',
username: 'ali',
);
test('should call the [AuthRepository.singIn()]', () async {
//arrange
when(
() => authRepository.signIn(
email: params.email,
password: params.password,
),
).thenAnswer((_) async => Right<Failure, UserEntity>(user));
//act
final Either<Failure, void> result = await signInUseCase(params);
// assert
expect(
result,
equals(
Right<Failure, UserEntity>(user),
),
);
verify(
() => authRepository.signIn(
email: params.email,
password: params.password,
),
).called(1);
verifyNoMoreInteractions(authRepository);
});
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase | mirrored_repositories/amazox_prime/test/lib/unit/domain/usecase/auth/log_out_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
class MockAuthRepository extends Mock implements AuthRepository {}
void main() {
late LogOutUseCase logOutUseCase;
late AuthRepository authRepository;
setUp(
() {
authRepository = MockAuthRepository();
logOutUseCase = LogOutUseCase(authRepository);
},
);
LogOutUseCaseParams params = LogOutUseCaseParams();
test(
'should call the [AuthRepository.logOut()]',
() async {
//arrange
when<Future<Either<Failure, void>>>(
() => authRepository.logOut(),
).thenAnswer((_) async => const Right<Failure, void>(null));
//act
final Either<Failure, void> result = await logOutUseCase(params);
// assert
expect(
result,
equals(
const Right<Failure, void>(null),
),
);
verify(
() => authRepository.logOut(),
).called(1);
verifyNoMoreInteractions(authRepository);
},
);
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/widget | mirrored_repositories/amazox_prime/test/lib/widget/core_ui/test_wrapper_widget.dart | import 'package:testing/test.dart';
class TestWrapper extends StatelessWidget {
final Widget _widget;
const TestWrapper({
required Widget widget,
super.key,
}) : _widget = widget;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _widget,
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/widget | mirrored_repositories/amazox_prime/test/lib/widget/core_ui/app_button_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
void main() {
testWidgets(
'test app button',
(WidgetTester widgetTester) async {
await widgetTester.pumpWidget(TestWrapper(
widget: PrimaryAppButton(
icon: Icons.add,
onPress: () {},
),
));
Finder button = find.byType(GestureDetector);
expect(button, findsOneWidget);
Finder icon = find.byIcon(AppIcons.increment);
expect(
icon,
findsOneWidget,
);
await widgetTester.tap(
button,
warnIfMissed: false,
);
await widgetTester.pump();
expect(
button,
findsOneWidget,
);
},
);
}
| 0 |
mirrored_repositories/amazox_prime/test/lib/widget | mirrored_repositories/amazox_prime/test/lib/widget/core_ui/app_text_field_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:testing/test.dart';
void main() {
final TextEditingController textEditingController = TextEditingController();
const String testText = 'test';
testWidgets(
'test app text field',
(WidgetTester tester) async {
await tester.pumpWidget(
TestWrapper(
widget: AppTextField(
controller: textEditingController,
),
),
);
Finder finder = find.byType(TextField);
expect(
finder,
findsOneWidget,
);
await tester.enterText(
find.byType(TextField),
testText,
);
expect(
textEditingController.text,
testText,
);
},
);
}
| 0 |
mirrored_repositories/amazox_prime/features/card | mirrored_repositories/amazox_prime/features/card/lib/shopping_card.dart | library cart;
export 'package:card/bloc/cart_bloc.dart';
export 'package:card/ui/components/cart_body.dart';
export 'package:card/ui/components/cart_list_item.dart';
export 'package:card/ui/components/cart_sublist.dart';
export 'package:card/ui/components/cart_total_price.dart';
export 'package:card/ui/components/empty_cart.dart';
export 'package:card/ui/page/shopping_card.dart';
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:domain/domain.dart';
export 'package:flutter/material.dart';
| 0 |
mirrored_repositories/amazox_prime/features/card/lib | mirrored_repositories/amazox_prime/features/card/lib/bloc/cart_event.dart | part of 'cart_bloc.dart';
@immutable
abstract class CartEvent extends Equatable {
const CartEvent();
@override
List<Object> get props => <Object>[];
}
class LoadCart extends CartEvent {}
class AddProduct extends CartEvent {
final Product product;
const AddProduct(this.product);
@override
List<Object> get props => <Object>[
product,
];
}
class RemoveProduct extends CartEvent {
final Product product;
const RemoveProduct(this.product);
@override
List<Object> get props => <Object>[
product,
];
}
final class RemoveAllProducts extends CartEvent {
const RemoveAllProducts();
@override
List<Object> get props => <Object>[];
}
final class ConfirmOrder extends CartEvent {
@override
List<Object> get props => <Object>[];
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib | mirrored_repositories/amazox_prime/features/card/lib/bloc/cart_bloc.dart | import 'dart:async';
import 'package:card/shopping_card.dart';
part 'cart_event.dart';
part 'cart_state.dart';
class CartBloc extends Bloc<CartEvent, CartState> {
final GetAllCartItemsUseCase _getAllCartItemsUseCase;
final AddCartItemUseCase _addCartItemUseCase;
final RemoveCartItemUseCase _removeCartItemUseCase;
final RemoveAllCartItemsUseCase _removeAllCartItemsUseCase;
final SaveUserOrderUseCase _saveUserOrderUseCase;
final SaveOrderRemoteUseCase _saveOrderRemoteUseCase;
CartBloc({
required GetAllCartItemsUseCase getAllCartItemsUseCase,
required AddCartItemUseCase addCartItemUseCase,
required SaveUserOrderUseCase saveUserOrderUseCase,
required RemoveCartItemUseCase removeCartItemUseCase,
required RemoveAllCartItemsUseCase removeAllCartItemsUseCase,
required SaveOrderRemoteUseCase saveOrderRemoteUseCase,
}) : _getAllCartItemsUseCase = getAllCartItemsUseCase,
_saveOrderRemoteUseCase = saveOrderRemoteUseCase,
_addCartItemUseCase = addCartItemUseCase,
_saveUserOrderUseCase = saveUserOrderUseCase,
_removeCartItemUseCase = removeCartItemUseCase,
_removeAllCartItemsUseCase = removeAllCartItemsUseCase,
super(CartLoading()) {
on<LoadCart>(_onLoadCart);
on<AddProduct>(_onAddProduct);
on<RemoveProduct>(_onRemoveProduct);
on<RemoveAllProducts>(_onRemoveAllProducts);
on<ConfirmOrder>(_onConfirmOrder);
}
void _onLoadCart(
LoadCart event,
Emitter<CartState> emit,
) async {
emit(CartLoading());
try {
emit(
CartLoaded(
cart: Cart(
cartItems: _getAllCartItemsUseCase(),
),
),
);
} catch (message) {
emit(
CartFailure(message: message.toString()),
);
}
}
void _onAddProduct(
AddProduct event,
Emitter<CartState> emit,
) {
if (state is CartLoaded) {
try {
_addCartItemUseCase.add(event.product);
emit(
CartLoaded(
cart: Cart(
cartItems:
List<Product>.from((state as CartLoaded).cart.cartItems)
..add(event.product),
),
),
);
} catch (message) {
emit(
CartFailure(message: message.toString()),
);
}
}
}
void _onRemoveProduct(
RemoveProduct event,
Emitter<CartState> emit,
) {
if (state is CartLoaded) {
try {
_removeCartItemUseCase.remove(event.product);
emit(
CartLoaded(
cart: Cart(
cartItems:
List<Product>.from((state as CartLoaded).cart.cartItems)
..remove(event.product),
),
),
);
} catch (message) {
emit(
CartFailure(
message: message.toString(),
),
);
}
}
}
Future<void> _onRemoveAllProducts(
RemoveAllProducts event,
Emitter<CartState> emit,
) async {
if (state is CartLoaded) {
await _saveUserOrderUseCase(
order: UserOrder(
id: const Uuid().v1(),
dateTime: date,
products: (state as CartLoaded).cart.cartItems,
price: totalPrice,
),
);
_removeAllCartItemsUseCase();
emit(
CartLoaded(
cart: Cart(
cartItems: List<Product>.from(
(state as CartLoaded).cart.cartItems,
)..clear(),
),
),
);
}
}
double get subtotal => (state as CartLoaded).cart.cartItems.fold(
0,
(double previousValue, Product element) =>
previousValue + element.price,
);
String get getSubtotalString => subtotal.toStringAsFixed(2);
double deliveryFee(subtotal) {
if (subtotal >= 2000) {
return 0;
} else {
return 200;
}
}
double total(subtotal, deliveryFee, serviceFee) {
return subtotal + deliveryFee(subtotal) + serviceFee;
}
double get totalPrice =>
total(subtotal, deliveryFee, (state as CartLoaded).serviceFee);
String get totalString =>
total(subtotal, deliveryFee, (state as CartLoaded).serviceFee)
.toStringAsFixed(2);
String get deliveryFeeString => deliveryFee(subtotal).toStringAsFixed(2);
String get date => DateTime.now().toString().substring(0, 10);
Future<void> _onConfirmOrder(
ConfirmOrder event,
Emitter<CartState> emit,
) async {
try {
final List<Product> cart = (state as CartLoaded).cart.cartItems;
_saveOrderRemoteUseCase(
order: UserOrder(
id: const Uuid().v4(),
dateTime: DateTime.now().toString().substring(0, 10),
products: cart
.map((Product e) => Product(
name: e.name,
description: e.description,
image: e.image,
price: e.price,
ml: e.ml,
id: e.id,
bigDescription: e.bigDescription,
rate: e.rate))
.toList(),
price: totalPrice,
),
);
} catch (message) {
emit(CartFailure(message: message.toString()));
}
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib | mirrored_repositories/amazox_prime/features/card/lib/bloc/cart_state.dart | part of 'cart_bloc.dart';
@immutable
abstract class CartState extends Equatable {
const CartState();
@override
List<Object> get props => <Object>[];
}
class CartLoading extends CartState {
@override
List<Object> get props => <Object>[];
}
class CartLoaded extends CartState {
final Cart cart;
final int serviceFee;
const CartLoaded({
this.cart = const Cart(),
this.serviceFee = 70,
});
@override
List<Object> get props => <Object>[
cart,
];
}
class CartFailure extends CartState {
final String message;
const CartFailure({
required this.message,
});
@override
List<Object> get props => <Object>[
message,
];
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/page/shopping_card.dart | import 'package:card/shopping_card.dart';
class ShappingCard extends StatefulWidget {
const ShappingCard({super.key});
@override
State<ShappingCard> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<ShappingCard> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<CartBloc, CartState>(
builder: (BuildContext context, CartState state) {
if (state is CartLoaded) {
if (state.cart.cartItems.isNotEmpty) {
return CartBody(
state: state,
);
} else {
return const EmptyCartBody();
}
} else if (state is CartLoading) {
return const Center(
child: CircularProgressIndicator.adaptive(
backgroundColor: ApplicationColors.primaryButtonColor,
),
);
} else {
return const Center(
child: SizedBox.shrink(),
);
}
},
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/components/cart_list_item.dart | import 'package:card/shopping_card.dart';
import 'package:core/enums/currency.dart';
class CartListItem extends StatelessWidget {
const CartListItem({
required this.product,
super.key,
});
final Product product;
@override
Widget build(BuildContext context) {
return ListTile(
trailing: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
PrimaryAppButton(
icon: AppIcons.increment,
onPress: () {
//TODO: Add increment
},
),
Text(
Dimensions.SIZE_1.toInt().toString(),
),
PrimaryAppButton(
icon: AppIcons.increment,
onPress: () {
//TODO: Adddecrement
},
)
]),
subtitle: RichText(
text: TextSpan(
text: '${product.price.toString()} ${Currency.rubl.value}',
style: AppFonts.normal16.copyWith(
color: ApplicationColors.black,
),
children: <InlineSpan>[
TextSpan(
text: ' ${product.ml}',
style: AppFonts.normal10.copyWith(
color: ApplicationColors.black,
),
),
],
),
),
title: Text(
overflow: TextOverflow.clip,
softWrap: true,
product.name,
style: AppFonts.normal12,
),
leading: Card(
clipBehavior: Clip.antiAlias,
child: CachedNetworkImage(
fadeInCurve: Curves.bounceInOut,
imageUrl: product.image,
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/components/cart_body.dart | import 'package:card/shopping_card.dart';
class CartBody extends StatefulWidget {
final CartLoaded _state;
const CartBody({
required CartLoaded state,
super.key,
}) : _state = state;
@override
State<CartBody> createState() => _CartBodyState();
}
class _CartBodyState extends State<CartBody> {
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: const CartTotalPrice(),
appBar: AppBar(
actions: <Widget>[
_deleteAllCartItems(),
],
title: const Text(
StringConstant.cart,
),
),
body: CustomScrollView(
slivers: <Widget>[
SliverList.builder(
itemCount: widget._state.cart.cartItems.length,
itemBuilder: (BuildContext context, int index) {
final Product product = widget._state.cart.cartItems[index];
return Slidable(
direction: Axis.horizontal,
endActionPane:
ActionPane(motion: const ScrollMotion(), children: <Widget>[
SlidableAction(
onPressed: (BuildContext context) {
context.read<CartBloc>().add(
RemoveProduct(product),
);
},
borderRadius: const BorderRadius.all(
Radius.circular(
Dimensions.SIZE_14,
),
),
backgroundColor: ApplicationColors.red,
foregroundColor: ApplicationColors.white,
icon: AppIcons.delete,
label: StringConstant.delete,
),
SlidableAction(
onPressed: (BuildContext context) {
//TODO: Add share feature
},
borderRadius: const BorderRadius.all(
Radius.circular(
Dimensions.SIZE_14,
),
),
backgroundColor: ApplicationColors.primaryButtonColor,
foregroundColor: ApplicationColors.white,
icon: AppIcons.share,
label: StringConstant.share,
),
]),
child: Padding(
padding: const EdgeInsets.all(
ApplicationPadding.PADDING_10,
),
child: CartListItem(
product: product,
),
),
);
},
),
CartSubList(state: widget._state),
],
),
);
}
BlocBuilder<CartBloc, CartState> _deleteAllCartItems() {
return BlocBuilder<CartBloc, CartState>(
builder: (BuildContext context, CartState state) {
return GestureDetector(
onTap: () {
context.read<CartBloc>().add(
const RemoveAllProducts(),
);
final SnackBar snackBar = SnackBar(
elevation: Dimensions.SIZE_10,
behavior: SnackBarBehavior.fixed,
backgroundColor: Colors.transparent,
content: AwesomeSnackbarContent(
inMaterialBanner: true,
message: StringConstant.emptyCartSnackBarSubtitle,
title: StringConstant.emptyCartSnackBarTitle,
color: ApplicationColors.primaryButtonColor,
contentType: ContentType.success,
),
);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(snackBar);
},
child: const Padding(
padding: EdgeInsets.symmetric(
horizontal: ApplicationPadding.PADDING_20,
),
child: Icon(
Icons.delete_outline_outlined,
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/components/cart_sublist.dart | import 'package:card/shopping_card.dart';
import 'package:core/enums/currency.dart';
class CartSubList extends StatelessWidget {
final CartLoaded _state;
const CartSubList({
required CartLoaded state,
super.key,
}) : _state = state;
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.sizeOf(context);
return SliverList(
key: const ValueKey<String>(
StringConstant.key,
),
delegate: SliverChildListDelegate(
<Widget>[
ListTile(
onTap: () {
showBottomSheet(
backgroundColor: ApplicationColors.white,
clipBehavior: Clip.antiAlias,
context: context,
builder: (BuildContext context) {
return SizedBox(
height: size.height / Dimensions.SIZE_4,
width: size.width,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
StringConstant.delivery,
style: AppFonts.normal24,
),
Text(
StringConstant.deliverySubtitle,
textAlign: TextAlign.center,
style: AppFonts.normal14.copyWith(),
)
],
),
);
},
);
},
title: const Text(StringConstant.delivery),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'${context.read<CartBloc>().deliveryFeeString} ${Currency.rubl.value}',
style: AppFonts.normal14,
),
AppIcons.chevronRightOutlined
],
),
),
ListTile(
title: const Text(
StringConstant.serviceFee,
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'${_state.serviceFee} ${Currency.rubl.value}',
style: AppFonts.normal14,
),
AppIcons.chevronRightOutlined
],
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/components/empty_cart.dart | import 'package:card/shopping_card.dart';
class EmptyCartBody extends StatelessWidget {
const EmptyCartBody({
super.key,
});
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.sizeOf(context);
return Scaffold(
appBar: AppBar(
title: const Text(
StringConstant.cart,
),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
SizedBox(
height: size.height / Dimensions.SIZE_4,
width: size.width / Dimensions.SIZE_2,
child: Lottie.asset(
animate: true,
ImagePaths.emptyCart,
repeat: true,
),
),
Column(
children: <Widget>[
Text(
StringConstant.notingIntoCartTitle,
style: AppFonts.bold18,
),
SizedBox(
height: size.height / Dimensions.SIZE_20,
),
const Text(
StringConstant.nothingIntoCartSubtitle,
textAlign: TextAlign.center,
)
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/card/lib/ui | mirrored_repositories/amazox_prime/features/card/lib/ui/components/cart_total_price.dart | import 'package:card/shopping_card.dart';
import 'package:core/enums/currency.dart';
class CartTotalPrice extends StatelessWidget {
const CartTotalPrice({
super.key,
});
@override
Widget build(BuildContext context) {
return Card(
clipBehavior: Clip.antiAlias,
child: SizedBox(
height: Dimensions.SIZE_88,
child: Padding(
padding: const EdgeInsets.all(
ApplicationPadding.PADDING_10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'${context.read<CartBloc>().totalString} ${Currency.rubl.value}',
style: AppFonts.normal24,
),
CartButton(
text: StringConstant.makeOrder,
onPressed: () {
context.read<CartBloc>().add(
ConfirmOrder(),
);
context.read<CartBloc>().add(
const RemoveAllProducts(),
);
final SnackBar snackBar = SnackBar(
elevation: Dimensions.SIZE_10,
behavior: SnackBarBehavior.fixed,
backgroundColor: Colors.transparent,
content: AwesomeSnackbarContent(
inMaterialBanner: true,
message: StringConstant.deliverySubtitle,
title: StringConstant.orderSnackBarTitle,
color: ApplicationColors.primaryButtonColor,
contentType: ContentType.success,
),
);
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(snackBar);
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin | mirrored_repositories/amazox_prime/features/admin/lib/admin.dart | library admin;
export 'package:admin/bloc/admin/admin_bloc.dart';
export 'package:admin/bloc/users/bloc/users_bloc.dart';
export 'package:admin/ui/page/admin/page/admin_page.dart';
export 'package:admin/ui/page/dashboard/admin_dashboard_page.dart';
export 'package:admin/ui/page/product_count/product_counts_page.dart';
export 'package:admin/ui/page/sales/sales_page.dart';
export 'package:admin/ui/page/users/components/bar_chart.dart';
export 'package:admin/ui/page/users/components/card.dart';
export 'package:admin/ui/page/users/page/app_users_page.dart';
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:navigation/navigation.dart';
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc | mirrored_repositories/amazox_prime/features/admin/lib/bloc/admin/admin_event.dart | part of 'admin_bloc.dart';
@immutable
sealed class AdminEvent {}
final class PickImageFromGalleryEvent extends AdminEvent {}
final class SaveProductEvent extends AdminEvent {
final Product product;
SaveProductEvent({required this.product});
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc | mirrored_repositories/amazox_prime/features/admin/lib/bloc/admin/admin_state.dart | part of 'admin_bloc.dart';
@immutable
sealed class AdminState {}
final class AdminInitial extends AdminState {}
final class ImagePickedFromGalleryState extends AdminState {
final String imageFromGallery;
ImagePickedFromGalleryState({
required this.imageFromGallery,
});
}
final class SavedProductState extends AdminState {}
final class AdminFailedState extends AdminState {
final String errorMessage;
AdminFailedState({required this.errorMessage});
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc | mirrored_repositories/amazox_prime/features/admin/lib/bloc/admin/admin_bloc.dart | import 'dart:io';
import 'package:admin/admin.dart';
part 'admin_event.dart';
part 'admin_state.dart';
class AdminBloc extends Bloc<AdminEvent, AdminState> {
final ImagePicker _imagePicker;
final SaveProductUseCase _saveProductUseCase;
File? pickedImage;
AdminBloc({
required ImagePicker imagePicker,
required SaveProductUseCase saveProductUseCase,
}) : _imagePicker = imagePicker,
_saveProductUseCase = saveProductUseCase,
super(AdminInitial()) {
on<PickImageFromGalleryEvent>(_onPickImageFromGallery);
on<SaveProductEvent>(_onSaveProductEvent);
}
Future<void> _onPickImageFromGallery(
PickImageFromGalleryEvent event,
Emitter<AdminState> emit,
) async {
try {
final XFile? xFile = await _imagePicker.pickImage(
source: ImageSource.gallery,
);
if (xFile == null) return;
pickedImage = File(xFile.path);
} catch (e) {
emit(AdminFailedState(errorMessage: e.toString()));
}
}
Future<void> _onSaveProductEvent(
SaveProductEvent event,
Emitter<AdminState> emit,
) async {
await _saveProductUseCase(
event.product,
pickedImage ??
File(
StringConstant.emptyString,
));
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc/users | mirrored_repositories/amazox_prime/features/admin/lib/bloc/users/bloc/users_event.dart | part of 'users_bloc.dart';
@immutable
sealed class UsersEvent {}
final class FetchAllUsersPerDayEvent extends UsersEvent {}
final class CloseBottomSheetEvent extends UsersEvent {}
final class ShowDailyUserStaticsPressed extends UsersEvent {}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc/users | mirrored_repositories/amazox_prime/features/admin/lib/bloc/users/bloc/users_state.dart | part of 'users_bloc.dart';
@immutable
sealed class UsersState {}
final class UsersInitial extends UsersState {}
final class UsersLoading extends UsersState {}
class UsersLoaded extends UsersState {
final List<int> usersByDate;
final List<UserEntity> users;
final List<int> ordersByDate;
UsersLoaded({
required this.ordersByDate,
required this.usersByDate,
required this.users,
});
UsersLoaded copyWith({
bool? isShowDailyUserStatics,
List<int>? usersByDate,
List<UserEntity>? users,
List<int>? ordersByDate,
}) {
return UsersLoaded(
ordersByDate: ordersByDate ?? this.ordersByDate,
usersByDate: usersByDate ?? this.usersByDate,
users: users ?? this.users,
);
}
}
final class UsersFailed extends UsersState {}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/bloc/users | mirrored_repositories/amazox_prime/features/admin/lib/bloc/users/bloc/users_bloc.dart | import 'package:admin/admin.dart';
part 'users_event.dart';
part 'users_state.dart';
class UsersBloc extends Bloc<UsersEvent, UsersState> {
final FetchAllUsersPerDayUseCase _fetchAllUsersPerDayUseCase;
final FetchAllUserByRegistrationDateUseCase
_fetchAllUsersByRegistrationDateUseCase;
final AppRouter _appRouter;
final GetOrdersPerDayUseCase _getOrdersPerDayUseCase;
bool isShowingDailyUser = false;
UsersBloc(
{required FetchAllUsersPerDayUseCase fetchAllUserUseCase,
required FetchAllUserByRegistrationDateUseCase
fetchAllUsersByRegistrationDateUseCase,
required AppRouter appRouter,
required GetOrdersPerDayUseCase getOrdersPerDayUseCase})
: _fetchAllUsersPerDayUseCase = fetchAllUserUseCase,
_fetchAllUsersByRegistrationDateUseCase =
fetchAllUsersByRegistrationDateUseCase,
_appRouter = appRouter,
_getOrdersPerDayUseCase = getOrdersPerDayUseCase,
super(UsersInitial()) {
on<FetchAllUsersPerDayEvent>(_onFetchAllUsersPerDay);
on<CloseBottomSheetEvent>(_onCloseBottomSheet);
on<ShowDailyUserStaticsPressed>(onDailyUserStaticsPressed);
add(FetchAllUsersPerDayEvent());
}
Future<void> _onFetchAllUsersPerDay(
FetchAllUsersPerDayEvent event,
Emitter<UsersState> emit,
) async {
emit(UsersLoading());
try {
final List<int> usersCount = await _fetchAllUsersPerDayUseCase();
final List<UserEntity> users =
await _fetchAllUsersByRegistrationDateUseCase();
final List<int> ordersCount = await _getOrdersPerDayUseCase();
emit(UsersLoaded(
ordersByDate: ordersCount,
usersByDate: usersCount,
users: users,
));
} catch (e) {
emit(UsersFailed());
}
}
Future<void> _onCloseBottomSheet(
CloseBottomSheetEvent event,
Emitter<UsersState> emit,
) async {
await _appRouter.pop();
}
bool changeBarChartState() {
return isShowingDailyUser = !isShowingDailyUser;
}
Future<void> onDailyUserStaticsPressed(
ShowDailyUserStaticsPressed event,
Emitter<UsersState> emit,
) async {
changeBarChartState();
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/product_count/product_counts_page.dart | import 'package:admin/admin.dart';
class ProductCountPage extends StatelessWidget {
const ProductCountPage({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page/admin | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/admin/page/admin_page.dart | import 'dart:math';
import 'package:admin/admin.dart';
class AdminPage extends StatelessWidget {
final TextEditingController _productNameTextEditingController =
TextEditingController();
final TextEditingController _productPriceTextEditingController =
TextEditingController();
final TextEditingController _productDescriptionTextEditingController =
TextEditingController();
AdminPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<AdminBloc>(
create: (BuildContext context) {
return AdminBloc(
imagePicker: getIt<ImagePicker>(),
saveProductUseCase: getIt<SaveProductUseCase>());
},
child: BlocBuilder<AdminBloc, AdminState>(
builder: (BuildContext context, AdminState state) {
if (state is AdminInitial) {
return Scaffold(
backgroundColor: ApplicationColors.pageBackground,
body: SafeArea(
child: ListView(
children: <Widget>[
const ImagePlaceHolder(),
const SizedBox(height: Dimensions.SIZE_20),
Padding(
padding: const EdgeInsets.all(Dimensions.SIZE_16),
child: Column(
children: <Widget>[
AppTextField(
suffixIcon:
const Icon(Icons.production_quantity_limits),
hintText: StringConstant.productName,
controller: _productNameTextEditingController,
fillColor: ApplicationColors.white,
filled: true,
),
const SizedBox(height: Dimensions.SIZE_20),
AppTextField(
suffixIcon:
const Icon(Icons.monetization_on_outlined),
hintText: StringConstant.productPrice,
controller: _productPriceTextEditingController,
keyboardType: TextInputType.number,
fillColor: ApplicationColors.white,
filled: true,
),
const SizedBox(height: Dimensions.SIZE_20),
SizedBox(
height: Dimensions.SIZE_500,
child: AppTextField(
hintText: StringConstant.productDescription,
isDescription: true,
fillColor: ApplicationColors.white,
filled: true,
maxLines: Dimensions.SIZE_20.toInt(),
controller:
_productDescriptionTextEditingController,
),
),
const SizedBox(height: Dimensions.SIZE_20),
CartButton(
onPressed: () {
if (_productNameTextEditingController
.text.isEmpty ||
_productPriceTextEditingController
.text.isEmpty ||
_productDescriptionTextEditingController
.text.isEmpty) {
Utils.showSnackBar(
context, 'Надо добавить товар');
} else {
context.read<AdminBloc>().add(
SaveProductEvent(
product: Product(
name:
_productNameTextEditingController
.text,
description:
_productDescriptionTextEditingController
.text,
image: StringConstant.emptyString,
price: int.parse(
_productPriceTextEditingController
.text),
ml: 10,
id: Random().nextInt(100000),
bigDescription:
_productDescriptionTextEditingController
.text,
rate: 10),
),
);
Utils.showSnackBar(context, 'Товар добавлень');
_productDescriptionTextEditingController
.clear();
_productPriceTextEditingController.clear();
_productNameTextEditingController.clear();
}
},
text: StringConstant.add,
)
],
),
)
],
),
),
);
} else {
return const Scaffold();
}
},
),
);
}
}
class ImagePlaceHolder extends StatelessWidget {
const ImagePlaceHolder({
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(Dimensions.SIZE_44),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
InkWell(
splashColor: ApplicationColors.primaryButtonColor,
borderRadius: BorderRadius.circular(Dimensions.SIZE_20),
onTap: () {
context.read<AdminBloc>().add(PickImageFromGalleryEvent());
},
child: Container(
height: 200,
width: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: ApplicationColors.contentColorPurple.withOpacity(0.6),
boxShadow: <BoxShadow>[
BoxShadow(
blurRadius: 10,
spreadRadius: 10,
color: ApplicationColors.contentColorPurple
.withOpacity(0.4)),
BoxShadow(
blurRadius: 20,
spreadRadius: 8,
color: ApplicationColors.primaryButtonColor
.withOpacity(0.5)),
]),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset('assets/images/image_placeholder.png'),
),
),
),
const SizedBox(height: 20),
Text(
'Выбери фото с расмером 650x650',
style: AppFonts.bold14.apply(color: ApplicationColors.white),
textAlign: TextAlign.center,
),
],
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/dashboard/admin_dashboard_page.dart | import 'package:admin/admin.dart';
class AdminDashBoardPage extends StatelessWidget {
const AdminDashBoardPage({super.key});
@override
Widget build(BuildContext context) {
return AutoTabsScaffold(
routes: <PageRouteInfo>[
const AdminHome(),
const UsersPageRouter(),
AdminPageRouter(),
const SalesPageRouter(),
],
animationCurve: Curves.easeIn,
backgroundColor: ApplicationColors.pageBackground,
bottomNavigationBuilder: (_, TabsRouter tabsRouter) {
return Padding(
padding: const EdgeInsets.all(
ApplicationPadding.PADDING_10,
),
child: Expanded(
child: ApplicationBottomAppBar(
currentIndex: tabsRouter.activeIndex,
onTap: tabsRouter.setActiveIndex,
items: <AppBarItem>[
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.home,
title: const Text(StringConstant.productsCount),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.users,
title: const Text(
StringConstant.users,
),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.add,
title: const Text(
StringConstant.add,
),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.products,
title: const Text(
StringConstant.productsCount,
),
),
],
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/sales/sales_page.dart | import 'package:admin/admin.dart';
class SalesPage extends StatelessWidget {
const SalesPage({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users/page/app_users_page.dart | import 'package:admin/admin.dart';
class AppUsersPage extends StatefulWidget {
const AppUsersPage({
super.key,
});
@override
State<AppUsersPage> createState() => _AppUsersPageState();
}
class _AppUsersPageState extends State<AppUsersPage> {
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: ApplicationColors.pageBackground,
body: BlocProvider<UsersBloc>(
create: (BuildContext context) => UsersBloc(
getOrdersPerDayUseCase: getIt<GetOrdersPerDayUseCase>(),
appRouter: getIt<AppRouter>(),
fetchAllUsersByRegistrationDateUseCase:
getIt<FetchAllUserByRegistrationDateUseCase>(),
fetchAllUserUseCase: getIt<FetchAllUsersPerDayUseCase>(),
),
child: BlocBuilder<UsersBloc, UsersState>(
builder: (BuildContext context, UsersState state) {
if (state is UsersLoading) {
return const CircularProgressIndicator.adaptive();
} else if (state is UsersLoaded) {
return Padding(
padding: const EdgeInsets.only(
top: Dimensions.SIZE_50,
),
child: ListView(
children: <Widget>[
Text(
context.watch<UsersBloc>().isShowingDailyUser
? StringConstant.salesStatics
: StringConstant.userStatics,
style: AppFonts.bold18.apply(
color: ApplicationColors.white,
),
textAlign: TextAlign.center,
),
Padding(
padding: const EdgeInsets.all(
Dimensions.SIZE_10,
),
child: SizedBox(
height: size.height / Dimensions.SIZE_2,
width: double.infinity,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.SIZE_20,
),
child: context.watch<UsersBloc>().isShowingDailyUser
? AppBarChart(
users: state.usersByDate,
orders: state.ordersByDate,
isShowSales: context
.watch<UsersBloc>()
.isShowingDailyUser,
)
: AppBarChart(
users: state.usersByDate,
orders: state.ordersByDate,
isShowSales: context
.watch<UsersBloc>()
.isShowingDailyUser,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
child: AdminCart(
onTap: () {
_showBottomSheet(
context,
size,
);
},
icon: Icons.supervised_user_circle_rounded,
text: StringConstant.usersLabel,
height: size.height / Dimensions.SIZE_6,
width: size.width / Dimensions.SIZE_5,
),
),
Expanded(
child: AdminCart(
onTap: () {
setState(() {});
context
.read<UsersBloc>()
.add(ShowDailyUserStaticsPressed());
},
icon: Icons.monetization_on,
text: StringConstant.sales,
height: size.height / Dimensions.SIZE_6,
width: size.width / Dimensions.SIZE_5,
),
),
],
),
],
),
);
} else {
return const Center(
child: Text(StringConstants.error),
);
}
},
),
),
);
}
void _showBottomSheet(BuildContext context, Size size) {
showBottomSheet(
backgroundColor: ApplicationColors.pageBackground,
clipBehavior: Clip.antiAlias,
context: context,
builder: (BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: Dimensions.SIZE_50),
child: BlocProvider<UsersBloc>(
create: (BuildContext context) => UsersBloc(
getOrdersPerDayUseCase: getIt<GetOrdersPerDayUseCase>(),
appRouter: getIt<AppRouter>(),
fetchAllUsersByRegistrationDateUseCase:
getIt<FetchAllUserByRegistrationDateUseCase>(),
fetchAllUserUseCase: getIt<FetchAllUsersPerDayUseCase>(),
),
child: BlocBuilder<UsersBloc, UsersState>(
builder: (BuildContext context, UsersState state) {
if (state is UsersFailed) {
return const Center(
child: Text(StringConstants.error),
);
}
if (state is UsersLoaded) {
return Stack(
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Text(
StringConstant.users,
style: AppFonts.bold18.apply(
color: ApplicationColors.white,
),
),
),
Padding(
padding: const EdgeInsets.only(top: Dimensions.SIZE_50),
child: SizedBox(
height: size.height,
width: size.width,
child: ListView.separated(
separatorBuilder:
(BuildContext context, int index) {
return const Divider(
endIndent: Dimensions.SIZE_8,
indent: Dimensions.SIZE_8,
color: ApplicationColors.primaryButtonColor,
);
},
shrinkWrap: true,
itemCount: state.users.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Row(
children: <Widget>[
CircleAvatar(
child: Image.asset(ImagePaths.user),
),
const SizedBox(
width: Dimensions.SIZE_16,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
'${StringConstant.postAddress}: ${state.users[index].email}',
style: AppFonts.bold14.apply(
color: ApplicationColors.white,
),
),
Text(
'${StringConstant.registrationDate}: ${DateFormat('dd.MM.yyyy').format(
state.users[index].registrationDate
.toDate(),
)}',
style: AppFonts.bold14.apply(
color: ApplicationColors.white,
),
)
],
),
],
),
);
},
),
),
),
Positioned(
right: Dimensions.SIZE_10,
child: GestureDetector(
onTap: () {
context
.read<UsersBloc>()
.add(CloseBottomSheetEvent());
},
child: const Icon(
Icons.close_rounded,
size: Dimensions.SIZE_26,
color: ApplicationColors.primaryButtonColor,
),
),
)
],
);
}
return const CircularProgressIndicator();
},
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users/components/card.dart | import 'package:admin/admin.dart';
class AdminCart extends StatelessWidget {
final String text;
final double height;
final double width;
final IconData icon;
final VoidCallback onTap;
const AdminCart({
required this.text,
required this.height,
required this.width,
required this.icon,
required this.onTap,
super.key,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(
Dimensions.SIZE_14,
),
child: GestureDetector(
onTap: onTap,
child: Card(
color: ApplicationColors.transparient,
elevation: Dimensions.SIZE_10,
child: Container(
width: width,
height: height,
decoration: BoxDecoration(
color: ApplicationColors.primaryButtonColor,
borderRadius: BorderRadius.circular(Dimensions.SIZE_16),
),
child: Stack(
children: <Widget>[
Positioned(
top: Dimensions.SIZE_8,
left: Dimensions.SIZE_14,
child: Icon(
icon,
size: Dimensions.SIZE_44,
color: ApplicationColors.pageBackground,
),
),
Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.SIZE_16,
),
child: Text(
textAlign: TextAlign.center,
text,
style: AppFonts.bold14.apply(
color: ApplicationColors.pageBackground,
),
),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users | mirrored_repositories/amazox_prime/features/admin/lib/ui/page/users/components/bar_chart.dart | import 'package:admin/admin.dart';
class AppBarChart extends StatelessWidget {
final bool isShowSales;
final List<int> orders;
final List<int> users;
const AppBarChart({
required this.users,
required this.isShowSales,
required this.orders,
super.key,
});
@override
Widget build(BuildContext context) {
return LineChart(
isShowSales ? salesData : usersData,
duration: DurationEnum.high.duration,
);
}
LineChartData get salesData => LineChartData(
lineTouchData: salesLineTouchData,
gridData: gridData,
titlesData: salesTitle,
borderData: borderData,
lineBarsData: salesBarData,
minX: Dimensions.SIZE_0,
maxX: Dimensions.SIZE_14,
maxY: Dimensions.SIZE_4,
minY: Dimensions.SIZE_0,
);
LineChartData get usersData => LineChartData(
lineTouchData: usersLineTouchData,
gridData: gridData,
titlesData: usersTitlesData,
borderData: borderData,
lineBarsData: <LineChartBarData>[
usersChartBarData,
],
minX: Dimensions.SIZE_0,
maxX: Dimensions.SIZE_14,
maxY: Dimensions.SIZE_6,
minY: Dimensions.SIZE_0,
);
LineTouchData get salesLineTouchData => LineTouchData(
handleBuiltInTouches: true,
touchTooltipData: LineTouchTooltipData(
tooltipBgColor: Colors.blueGrey.withOpacity(Dimensions.SIZE_0_8),
),
);
FlTitlesData get salesTitle => FlTitlesData(
bottomTitles: AxisTitles(
sideTitles: bottomTitles,
),
rightTitles: const AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
topTitles: const AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
leftTitles: AxisTitles(
sideTitles: leftTitles(),
),
);
List<LineChartBarData> get salesBarData => <LineChartBarData>[
orderChartBarData,
];
LineTouchData get usersLineTouchData => const LineTouchData(
enabled: false,
);
FlTitlesData get usersTitlesData => FlTitlesData(
bottomTitles: AxisTitles(
sideTitles: bottomTitles,
),
rightTitles: const AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
topTitles: const AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
leftTitles: AxisTitles(
sideTitles: leftTitles(),
),
);
Widget leftTitleWidgets(
double value,
TitleMeta meta,
) {
TextStyle style = AppFonts.bold14.apply(color: ApplicationColors.white);
String text;
switch (value.toInt()) {
case 1:
text = StringConstant.one;
break;
case 2:
text = StringConstant.two;
break;
case 3:
text = StringConstant.three;
break;
case 4:
text = StringConstant.four;
break;
case 5:
text = StringConstant.five;
break;
case 6:
text = StringConstant.six;
break;
default:
return Container();
}
return Text(
text,
style: style,
textAlign: TextAlign.center,
);
}
SideTitles leftTitles() => SideTitles(
getTitlesWidget: leftTitleWidgets,
showTitles: true,
interval: Dimensions.SIZE_1,
reservedSize: Dimensions.SIZE_40,
);
Widget bottomTitleWidgets(double value, TitleMeta meta) {
TextStyle style = AppFonts.bold14.apply(color: ApplicationColors.white);
Widget text;
switch (value.toInt()) {
case 2:
text = Text(StringConstant.september, style: style);
break;
case 7:
text = Text(StringConstant.october, style: style);
break;
case 12:
text = Text(StringConstant.december, style: style);
break;
default:
text = const Text('');
break;
}
return SideTitleWidget(
axisSide: meta.axisSide,
space: Dimensions.SIZE_10,
child: text,
);
}
SideTitles get bottomTitles => SideTitles(
showTitles: true,
reservedSize: Dimensions.SIZE_30,
interval: Dimensions.SIZE_1,
getTitlesWidget: bottomTitleWidgets,
);
FlGridData get gridData => const FlGridData(show: false);
FlBorderData get borderData => FlBorderData(
show: true,
border: Border(
bottom: BorderSide(
color: ApplicationColors.primary.withOpacity(Dimensions.SIZE_0_2),
width: Dimensions.SIZE_4),
left: const BorderSide(color: Colors.transparent),
right: const BorderSide(color: Colors.transparent),
top: const BorderSide(color: Colors.transparent),
),
);
LineChartBarData get orderChartBarData => LineChartBarData(
isCurved: true,
color: ApplicationColors.contentColorGreen
.withOpacity(Dimensions.SIZE_0_6),
barWidth: Dimensions.SIZE_6,
isStrokeCapRound: true,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(
show: true,
color: ApplicationColors.contentColorGreen
.withOpacity(Dimensions.SIZE_0_2),
),
spots: orders
.asMap()
.entries
.map((MapEntry<int, int> index) =>
FlSpot(index.key.toDouble(), index.value.toDouble()))
.toList(),
);
LineChartBarData get usersChartBarData => LineChartBarData(
isCurved: true,
color:
ApplicationColors.contentColorPink.withOpacity(Dimensions.SIZE_0_6),
barWidth: Dimensions.SIZE_6,
isStrokeCapRound: true,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(
show: true,
color:
ApplicationColors.contentColorPink.withOpacity(Dimensions.SIZE_0_2),
),
spots: users
.asMap()
.entries
.map((MapEntry<int, int> index) =>
FlSpot(index.key.toDouble(), index.value.toDouble()))
.toList());
}
| 0 |
mirrored_repositories/amazox_prime/features/dashboard | mirrored_repositories/amazox_prime/features/dashboard/lib/dashboard.dart | library dashboard;
export 'package:core_ui/constants/string.dart';
export 'package:dashboard/ui/dashboard_page.dart';
export 'package:flutter/material.dart';
export 'package:navigation/navigation.dart';
| 0 |
mirrored_repositories/amazox_prime/features/dashboard/lib | mirrored_repositories/amazox_prime/features/dashboard/lib/ui/dashboard_page.dart | import 'package:dashboard/dashboard.dart';
class DashboardView extends StatelessWidget {
const DashboardView({
super.key,
});
@override
Widget build(BuildContext context) {
return AutoTabsScaffold(
routes: const <PageRouteInfo>[
HomeRouter(),
ShappngCardRouter(),
OrderHistoryRouter(),
SettingsRouter(),
],
animationCurve: Curves.linearToEaseOut,
bottomNavigationBuilder: (_, tabsRouter) {
return Padding(
padding: const EdgeInsets.all(
ApplicationPadding.PADDING_10,
),
child: ApplicationBottomAppBar(
currentIndex: tabsRouter.activeIndex,
onTap: tabsRouter.setActiveIndex,
margin: const EdgeInsets.symmetric(
horizontal: Dimensions.SIZE_20,
vertical: Dimensions.SIZE_10,
),
items: <AppBarItem>[
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.home,
title: const Text(
StringConstant.home,
),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: BlocBuilder<CartBloc, CartState>(
builder: (context, state) {
if (state is CartLoaded) {
return Badge(
textColor: context.theme == ThemeData.dark()
? ApplicationColors.white
: ApplicationColors.black,
label: Text(
state.cart.cartItems.length.toString(),
),
child: AppIcons.cart);
} else {
return AppIcons.cart;
}
},
),
title: const Text(
StringConstant.cartt,
),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.order,
title: const Text(
StringConstant.order,
),
),
AppBarItem(
selectedColor: ApplicationColors.white,
icon: AppIcons.settings,
title: const Text(
StringConstant.settings,
),
),
],
),
);
},
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/order | mirrored_repositories/amazox_prime/features/order/lib/order.dart | library order;
export 'package:card/shopping_card.dart';
export 'package:core/constants/string_constants.dart';
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:domain/domain.dart';
export 'package:flutter/material.dart';
export 'package:order/bloc/order_bloc.dart';
export 'package:order/ui/components/order_date.dart';
export 'package:order/ui/components/order_price.dart';
export 'package:order/ui/page/order_history.dart';
| 0 |
mirrored_repositories/amazox_prime/features/order/lib | mirrored_repositories/amazox_prime/features/order/lib/bloc/order_event.dart | part of 'order_bloc.dart';
@immutable
abstract class OrderEvent extends Equatable {}
final class FetchAllOrders extends OrderEvent {
@override
List<Object?> get props => <Object?>[];
}
| 0 |
mirrored_repositories/amazox_prime/features/order/lib | mirrored_repositories/amazox_prime/features/order/lib/bloc/order_state.dart | part of 'order_bloc.dart';
@immutable
abstract class OrderState extends Equatable {}
final class OrdersLoading extends OrderState {
@override
List<Object?> get props => <Object?>[];
}
final class OrdersLoaded extends OrderState {
final List<UserOrder> orders;
OrdersLoaded({required this.orders});
@override
List<Object?> get props => <Object?>[
orders,
];
}
final class OrdersFailure extends OrderState {
@override
List<Object?> get props => <Object?>[];
}
| 0 |
mirrored_repositories/amazox_prime/features/order/lib | mirrored_repositories/amazox_prime/features/order/lib/bloc/order_bloc.dart | import 'dart:async';
import 'package:order/order.dart';
part 'order_event.dart';
part 'order_state.dart';
class OrderBloc extends Bloc<OrderEvent, OrderState> {
final GetAllUserOrdersUseCase _getAllUserOrders;
OrderBloc({
required GetAllUserOrdersUseCase getAllUserOrders,
}) : _getAllUserOrders = getAllUserOrders,
super(OrdersLoading()) {
on<FetchAllOrders>(_onFetchAllOrders);
}
Future<void> _onFetchAllOrders(
FetchAllOrders event,
Emitter<OrderState> emit,
) async {
try {
final List<UserOrder> orders = _getAllUserOrders();
emit(
OrdersLoaded(orders: orders),
);
} catch (e) {
emit(OrdersFailure());
}
}
}
| 0 |
mirrored_repositories/amazox_prime/features/order/lib/ui | mirrored_repositories/amazox_prime/features/order/lib/ui/page/order_history.dart | import 'package:order/order.dart';
class OrderHistoryPage extends StatefulWidget {
const OrderHistoryPage({super.key});
@override
State<OrderHistoryPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<OrderHistoryPage> {
@override
void initState() {
super.initState();
context.read<OrderBloc>().add(FetchAllOrders());
}
@override
Widget build(BuildContext context) {
return BlocBuilder<OrderBloc, OrderState>(
builder: (BuildContext context, OrderState state) {
if (state is OrdersLoaded) {
return Scaffold(
appBar: AppBar(
title: const Text(StringConstant.myOrders),
),
body: GradientBackground(
image: ImagePaths.authGradientBackground,
child: ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return const Divider();
},
itemCount: state.orders.length,
itemBuilder: (BuildContext context, int index) {
final UserOrder order = state.orders[index];
return SizedBox(
width: double.infinity,
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.all(
Dimensions.SIZE_10,
),
child: Column(
children: <Widget>[
Text(
'${StringConstant.productCount} ${order.products.length}',
style: AppFonts.bold16,
),
const SizedBox(height: Dimensions.SIZE_20),
_productImageCarousel(order),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
OrderPrice(order: order),
OrderDate(order: order)
],
),
],
),
)
]),
);
},
),
),
);
} else if (state is OrdersLoading) {
return const Center(child: CircularProgressIndicator());
} else {
return const Center(
child: Text(
StringConstants.error,
),
);
}
},
);
}
CarouselSlider _productImageCarousel(UserOrder order) {
return CarouselSlider.builder(
itemBuilder: (
BuildContext context,
int index,
int realIndex,
) {
return Column(
children: <Widget>[
Text(
order.products[index].name,
style: AppFonts.normal18,
overflow: TextOverflow.ellipsis,
),
Card(
clipBehavior: Clip.antiAlias,
child: Image.network(
order.products[index].image,
fit: BoxFit.fill,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
StringConstant.orderId,
style: AppFonts.bold12,
),
TextButton(
onPressed: () {
//TODO ADD copy product ID
},
child: Row(
children: <Widget>[
Text(
(order.products[index].id * Dimensions.SIZE_99,)
.toString()
.substring(1, 4),
style: AppFonts.bold12,
),
AppIcons.copy,
],
)),
],
),
],
);
},
itemCount: order.products.length,
options: CarouselOptions(
height: Dimensions.SIZE_300,
clipBehavior: Clip.antiAlias,
disableCenter: true,
initialPage: Dimensions.SIZE_2.toInt(),
autoPlayCurve: Curves.decelerate,
pageSnapping: true,
viewportFraction: Dimensions.SIZE_0_6,
autoPlay: true,
animateToClosest: true,
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/order/lib/ui | mirrored_repositories/amazox_prime/features/order/lib/ui/components/order_date.dart | import 'package:order/order.dart';
class OrderDate extends StatelessWidget {
const OrderDate({
super.key,
required this.order,
});
final UserOrder order;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(
StringConstant.date,
style: AppFonts.bold14,
),
Text(
order.dateTime,
),
],
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/order/lib/ui | mirrored_repositories/amazox_prime/features/order/lib/ui/components/order_price.dart | import 'package:core/enums/currency.dart';
import 'package:order/order.dart';
class OrderPrice extends StatelessWidget {
const OrderPrice({
required this.order,
super.key,
});
final UserOrder order;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(
StringConstant.total,
style: AppFonts.bold14,
),
Text('${order.price.toString()} ${Currency.rubl.name}')
],
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/onboarding | mirrored_repositories/amazox_prime/features/onboarding/lib/onboarding.dart | library onboarding;
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:domain/domain.dart';
export 'package:onboarding/cubit/on_boarding_cubit.dart';
export 'package:onboarding/onboarding.dart';
export 'package:onboarding/views/on_boarding_screen.dart';
export 'package:navigation/navigation.dart';
| 0 |
mirrored_repositories/amazox_prime/features/onboarding/lib | mirrored_repositories/amazox_prime/features/onboarding/lib/views/on_boarding_screen.dart | import 'package:onboarding/onboarding.dart';
import 'on_boarding_body.dart';
class OnBoardingScreen extends StatefulWidget {
const OnBoardingScreen({super.key});
@override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
PageController pageController = PageController();
@override
void initState() {
context.read<OnBoardingCubit>().checkIfUserIsFirstTimer();
super.initState();
}
@override
Widget build(BuildContext context) {
const int indicatorCount = 3;
return Scaffold(
backgroundColor: ApplicationColors.white,
body: BlocListener<OnBoardingCubit, bool>(
listener: (context, state) {
if (!state) {
context.read<OnBoardingCubit>().navigateToMain(
context: context,
);
}
},
child: GradientBackground(
image: ImagePaths.onBoardingBackground,
child: SafeArea(
child: Stack(
children: <Widget>[
PageView(
controller: pageController,
children: const <Widget>[
OnBoardingBody(pageContent: PageContent.first()),
OnBoardingBody(pageContent: PageContent.second()),
OnBoardingBody(pageContent: PageContent.third()),
],
),
Align(
alignment: const Alignment(0, .04),
child: SmoothPageIndicator(
controller: pageController,
count: indicatorCount,
onDotClicked: (index) {
pageController.animateToPage(
index,
duration: DurationEnum.normal.duration,
curve: Curves.easeInOut,
);
},
effect: const WormEffect(
dotHeight: Dimensions.SIZE_10,
dotWidth: Dimensions.SIZE_10,
spacing: Dimensions.SIZE_40,
activeDotColor: ApplicationColors.primaryButtonColor,
dotColor: ApplicationColors.primaryButtonColor,
),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/onboarding/lib | mirrored_repositories/amazox_prime/features/onboarding/lib/views/on_boarding_body.dart | import 'package:onboarding/onboarding.dart';
class OnBoardingBody extends StatelessWidget {
const OnBoardingBody({
required this.pageContent,
super.key,
});
final PageContent pageContent;
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
pageContent.image,
height: size.height / Dimensions.SIZE_3,
),
const SizedBox(
height: Dimensions.SIZE_20,
),
Padding(
padding: const EdgeInsets.all(
ApplicationPadding.PADDING_20,
).copyWith(
bottom: Dimensions.SIZE_0,
),
child: Column(
children: <Widget>[
Text(
pageContent.title,
textAlign: TextAlign.center,
style: AppFonts.normal24,
),
const SizedBox(height: Dimensions.SIZE_20),
Text(
pageContent.description,
textAlign: TextAlign.center,
style: AppFonts.normal14,
),
SizedBox(height: size.height * .05),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 50,
vertical: 17,
),
backgroundColor: ApplicationColors.primaryButtonColor,
foregroundColor: ApplicationColors.white,
),
onPressed: () async {
await context.read<OnBoardingCubit>().cacheFirstTimer();
if (context.mounted) {
await context
.read<OnBoardingCubit>()
.navigateToAuthOrHome(context: context);
}
},
child: Text(
StringConstant.getStarted,
style: AppFonts.normal24,
),
),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/onboarding/lib | mirrored_repositories/amazox_prime/features/onboarding/lib/cubit/on_boarding_cubit.dart | import 'package:onboarding/onboarding.dart';
class OnBoardingCubit extends Cubit<bool> {
final CacheFirstTimerUseCase _cacheFirstTimerUseCase;
final CheckIfUserIsFirstTimerUseCase _checkIfUserIsFirstTimerUseCase;
OnBoardingCubit({
required CacheFirstTimerUseCase cacheFirstTimer,
required CheckIfUserIsFirstTimerUseCase checkIfUserIsFirstTimer,
}) : _cacheFirstTimerUseCase = cacheFirstTimer,
_checkIfUserIsFirstTimerUseCase = checkIfUserIsFirstTimer,
super(true);
Future<void> cacheFirstTimer() async {
final Either<Failure, void> result = await _cacheFirstTimerUseCase();
result.fold(
(failure) => null,
(_) => null,
);
}
Future<void> checkIfUserIsFirstTimer() async {
final result = await _checkIfUserIsFirstTimerUseCase();
result.fold(
(failure) => null,
emit,
);
}
Future<void> navigateToMain({required BuildContext context}) async {
await AutoRouter.of(context).replace(DashBoardPage());
}
Future<void> navigateToAuthOrHome({required BuildContext context}) async {
await AutoRouter.of(context).replace(
FirebaseAuth.instance.currentUser == null
? SignInPage()
: DashBoardPage(),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details | mirrored_repositories/amazox_prime/features/product_details/lib/product_details.dart | library product_details;
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:flutter/material.dart';
export 'package:navigation/navigation.dart';
export 'package:product_details/bloc/details/details_bloc.dart';
export 'package:product_details/bloc/details/details_event.dart';
export 'package:product_details/bloc/details/details_state.dart';
export 'package:product_details/components/app_bar.dart';
export 'package:product_details/components/sliver_list.dart';
export 'package:product_details/product_details.dart';
export 'package:product_details/ui/product_details_page.dart';
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib | mirrored_repositories/amazox_prime/features/product_details/lib/components/sliver_list.dart | import 'package:product_details/product_details.dart';
class DetailsSliverList extends StatelessWidget {
const DetailsSliverList({
required this.size,
required this.data,
super.key,
});
final Size size;
final Product data;
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: <Widget>[
DetailsAppBar(
size: size,
data: data,
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(ApplicationPadding.PADDING_10),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
vertical: ApplicationPadding.PADDING_10,
),
child: Row(
children: <Widget>[
AppRatingBar(rate: data.rate.toDouble()),
const SizedBox(width: Dimensions.SIZE_20),
Text(
data.rate.toString(),
),
SizedBox(
width: size.width / Dimensions.SIZE_6,
),
Text(
'${data.price.toString()} ${Currency.rubl.value}',
style: AppFonts.bold24,
)
],
),
),
Text(
data.description,
style: AppFonts.normal16,
),
Padding(
padding: const EdgeInsets.only(
top: ApplicationPadding.PADDING_20,
),
child: Expanded(
child: Text(
data.bigDescription,
style: AppFonts.normal16,
),
),
),
Padding(
padding: const EdgeInsets.only(
top: ApplicationPadding.PADDING_20,
),
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
BlocBuilder<CartBloc, CartState>(
builder: (BuildContext context, CartState state) {
return Padding(
padding: const EdgeInsets.all(Dimensions.SIZE_10),
child: SizedBox(
height: Dimensions.SIZE_80,
width: size.width / Dimensions.SIZE_1_2,
child: CartButton(
onPressed: () {
context
.read<CartBloc>()
.add(AddProduct(data));
},
text: StringConstant.buy,
),
),
);
},
)
],
),
)
],
),
),
)
],
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib | mirrored_repositories/amazox_prime/features/product_details/lib/components/app_bar.dart | import 'package:product_details/product_details.dart';
class DetailsAppBar extends StatelessWidget {
const DetailsAppBar({
super.key,
required this.size,
required this.data,
});
final Size size;
final Product data;
@override
Widget build(BuildContext context) {
return SliverAppBar(
actions: <Widget>[
IconButton(
onPressed: () {
//TODO: Add action
},
icon: const Icon(
AppIcons.share,
color: ApplicationColors.white,
))
],
floating: true,
bottom: PreferredSize(
preferredSize: const Size.fromHeight(
Dimensions.SIZE_40,
),
child: Container(
width: size.width,
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(
Dimensions.SIZE_50,
),
topRight: Radius.circular(
Dimensions.SIZE_50,
),
),
color: ApplicationColors.white,
),
child: Padding(
padding: const EdgeInsets.only(),
child: Padding(
padding: const EdgeInsets.only(
top: Dimensions.SIZE_50,
left: ApplicationPadding.PADDING_20,
),
child: Text(
data.name,
style: AppFonts.bold18,
),
),
),
),
),
expandedHeight: size.height / Dimensions.SIZE_4,
flexibleSpace: FlexibleSpaceBar(
background: Hero(
tag: AppHeroTags.homeToDetails,
child: AppCachedNetworkImage(
url: data.image,
),
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib/bloc | mirrored_repositories/amazox_prime/features/product_details/lib/bloc/produc_count/product_count_cubit.dart | import 'package:product_details/product_details.dart';
class ProductCounterCubit extends Cubit<int> {
ProductCounterCubit() : super(1);
void incrementProductCount() => emit(
state + 1,
);
void decrementProductCount() {
if (state > 1) {
emit(state - 1);
}
}
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib/bloc | mirrored_repositories/amazox_prime/features/product_details/lib/bloc/details/details_bloc.dart | import 'package:product_details/product_details.dart';
class DetailsBloc extends Bloc<DetailsEvent, DetailsState> {
final FetchProductByIdUseCase _fetchProductByIdUseCase;
DetailsBloc(
FetchProductByIdUseCase fetchProductByIdUseCase,
) : _fetchProductByIdUseCase = fetchProductByIdUseCase,
super(
InitialDetailsState(),
) {
on<FetchProductEvent>(_fetchProductByIdEvent);
}
Future<void> _fetchProductByIdEvent(
FetchProductEvent event, Emitter<DetailsState> emit) async {
emit(LoadingDetailsState());
try {
final Product data = await _fetchProductByIdUseCase.call(
event.productId,
);
emit(
LoadedDetailsState(
product: data,
),
);
} catch (e) {
emit(
FailedDetailsState(
message: e.toString(),
),
);
}
}
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib/bloc | mirrored_repositories/amazox_prime/features/product_details/lib/bloc/details/details_event.dart | import 'package:product_details/product_details.dart';
@immutable
abstract class DetailsEvent {}
final class FetchProductEvent extends DetailsEvent {
final int productId;
FetchProductEvent({
required this.productId,
});
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib/bloc | mirrored_repositories/amazox_prime/features/product_details/lib/bloc/details/details_state.dart | import 'package:product_details/product_details.dart';
@immutable
abstract class DetailsState {}
final class InitialDetailsState extends DetailsState {}
final class LoadingDetailsState extends DetailsState {}
final class LoadedDetailsState extends DetailsState {
final Product product;
LoadedDetailsState({
required this.product,
});
LoadedDetailsState copyWith({
required Product product,
}) {
return LoadedDetailsState(
product: product,
);
}
}
final class FailedDetailsState extends DetailsState {
final String message;
FailedDetailsState({
required this.message,
});
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib | mirrored_repositories/amazox_prime/features/product_details/lib/di/di.dart | import 'package:product_details/product_details.dart';
void initDetails() {
getIt.registerLazySingleton<DetailsBloc>(
() => DetailsBloc(getIt()),
);
}
| 0 |
mirrored_repositories/amazox_prime/features/product_details/lib | mirrored_repositories/amazox_prime/features/product_details/lib/ui/product_details_page.dart | import 'package:product_details/bloc/produc_count/product_count_cubit.dart';
import 'package:product_details/product_details.dart';
class ProductDetailPage extends StatefulWidget {
final int productId;
const ProductDetailPage({
super.key,
@PathParam() required this.productId,
});
@override
State<ProductDetailPage> createState() => _ProductDetailPageState();
}
class _ProductDetailPageState extends State<ProductDetailPage> {
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.sizeOf(context);
return Scaffold(
body: MultiBlocProvider(
providers: [
BlocProvider(
lazy: true,
create: (BuildContext context) => DetailsBloc(
getIt.get<FetchProductByIdUseCase>(),
)..add(
FetchProductEvent(
productId: widget.productId,
),
),
),
BlocProvider(
create: (_) => ProductCounterCubit(),
lazy: true,
)
],
child: BlocBuilder<DetailsBloc, DetailsState>(
builder: (context, state) {
if (state is LoadedDetailsState) {
final Product data = state.product;
return Scaffold(
body: DetailsSliverList(
size: size,
data: data,
),
);
} else if (state is LoadingDetailsState) {
return const Center(
child: CircularProgressIndicator.adaptive(
backgroundColor: ApplicationColors.primaryButtonColor,
),
);
} else {
return const Center(
child: SizedBox.shrink(),
);
}
},
),
),
);
}
}
| 0 |
mirrored_repositories/amazox_prime/features/auth | mirrored_repositories/amazox_prime/features/auth/lib/auth.dart | library auth;
export 'package:auth/auth.dart';
export 'package:auth/bloc/auth_bloc.dart';
export 'package:auth/components/sign_in_button.dart';
export 'package:auth/components/sign_in_form.dart';
export 'package:auth/page/sign_in_screen.dart';
export 'package:auth/page/sign_up_screen.dart';
export 'package:auth/providers/user_provider.dart';
export 'package:core/core.dart';
export 'package:core_ui/core_ui.dart';
export 'package:domain/domain.dart';
export 'package:flutter/material.dart';
export 'package:navigation/navigation.dart';
| 0 |
mirrored_repositories/amazox_prime/features/auth/lib | mirrored_repositories/amazox_prime/features/auth/lib/page/sign_in_screen.dart | import 'package:auth/auth.dart';
class SignInScreen extends StatefulWidget {
const SignInScreen({super.key});
@override
State<SignInScreen> createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
GlobalKey<FormState> formKey = GlobalKey<FormState>();
final UserProvider userProvider = UserProvider();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ApplicationColors.white,
extendBodyBehindAppBar: true,
body: BlocConsumer<AuthBloc, AuthState>(
listener: (BuildContext context, AuthState state) {
if (state is AuthError) {
Utils.showSnackBar(
context,
state.message,
);
} else if (state is SignedInState) {
userProvider.initUser(state.user);
context.read<AuthBloc>().add(
NavigateTosHomePageEvent(),
);
}
},
builder: (BuildContext context, AuthState state) {
return GradientBackground(
image: ImagePaths.authGradientBackground,
child: SafeArea(
child: Center(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.SIZE_20,
),
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: Dimensions.SIZE_80,
),
child: Text(
StringConstant.signInSlogan,
style: AppFonts.normal32,
),
),
const SizedBox(
height: Dimensions.SIZE_10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Hero(
tag: AppHeroTags.helperText,
flightShuttleBuilder: AuthUtils.buildShuttle,
child: Text(
StringConstant.signInToYourAccount,
style: AppFonts.bold12,
),
),
Baseline(
baseline: Dimensions.SIZE_75,
baselineType: TextBaseline.alphabetic,
child: Hero(
tag: AppHeroTags.redirectText,
child: TextButton(
onPressed: () {
context.read<AuthBloc>().add(
NavigateToRegistrationPageEvent(),
);
},
child: const Text(
StringConstant.registration,
),
),
),
),
],
),
const SizedBox(
height: Dimensions.SIZE_10,
),
SignInForm(
emailController: emailController,
passwordController: passwordController,
formKey: formKey,
),
const SizedBox(
height: Dimensions.SIZE_20,
),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
//TODO add forgot password feature
},
child: const Text(
StringConstant.forgotPassword,
),
),
),
const SizedBox(
height: Dimensions.SIZE_20,
),
Hero(
tag: AppHeroTags.authButton,
child: state is AuthLoadingState
? const Center(
child: CircularProgressIndicator(),
)
: SignInButton(
formKey: formKey,
emailController: emailController,
passwordController: passwordController,
),
),
const SizedBox(
height: Dimensions.SIZE_10,
),
const Divider(),
const SizedBox(
height: Dimensions.SIZE_10,
),
Hero(
tag: AppHeroTags.authButton,
child: state is AuthLoadingState
? const Center(
child: CircularProgressIndicator(),
)
: SignInButton(
isGoogleButton: true,
formKey: formKey,
emailController: emailController,
passwordController: passwordController,
),
),
],
),
),
),
);
},
),
);
}
@override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/amazox_prime/features/auth/lib | mirrored_repositories/amazox_prime/features/auth/lib/page/sign_up_screen.dart | import 'package:auth/auth.dart';
import 'package:auth/components/sign_up_form.dart';
class SignUpScreen extends StatefulWidget {
const SignUpScreen({super.key});
@override
State<SignUpScreen> createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
TextEditingController emailController = TextEditingController();
TextEditingController fullNameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController confirmPasswordController = TextEditingController();
GlobalKey<FormState> formKey = GlobalKey<FormState>();
final UserProvider _userProvider = UserProvider();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
extendBodyBehindAppBar: true,
backgroundColor: ApplicationColors.white,
body: BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthError) {
Utils.showSnackBar(context, state.message);
} else if (state is SignedUpState) {
context.read<AuthBloc>().add(
SignInEvent(
email: emailController.text.trim(),
password: passwordController.text.trim(),
),
);
} else if (state is SignedInState) {
_userProvider.initUser(state.user);
context.read<AuthBloc>().add(
NavigateTosHomePageEvent(),
);
}
},
builder: (context, state) {
return GradientBackground(
image: ImagePaths.authGradientBackground,
child: SafeArea(
child: Center(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.SIZE_20,
),
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: Dimensions.SIZE_80,
),
child: Text(
StringConstant.signUpSlogan,
style: AppFonts.normal32,
),
),
const SizedBox(
height: Dimensions.SIZE_10,
),
Hero(
tag: AppHeroTags.helperText,
child: Text(
StringConstant.signUpToYourAccount,
style: AppFonts.normal14,
),
),
const SizedBox(
height: Dimensions.SIZE_10,
),
Hero(
tag: AppHeroTags.redirectText,
child: Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
context.read<AuthBloc>().add(
NavigateTosSignInPageEvent(),
);
},
child: const Text(
StringConstant.alreadyHaveAnAccount,
),
),
),
),
const SizedBox(
height: Dimensions.SIZE_10,
),
SignUpForm(
emailController: emailController,
passwordController: passwordController,
fullNameController: fullNameController,
confirmPasswordController: confirmPasswordController,
formKey: formKey,
),
const SizedBox(
height: Dimensions.SIZE_30,
),
Hero(
tag: AppHeroTags.authButton,
child: RoundedButton(
label: StringConstant.signUp,
onPressed: () {
FocusManager.instance.primaryFocus?.unfocus();
if (formKey.currentState!.validate()) {
context.read<AuthBloc>().add(
SignUpEvent(
email: emailController.text.trim(),
password: passwordController.text.trim(),
name: fullNameController.text.trim(),
),
);
}
},
),
),
],
),
),
),
);
},
),
);
}
@override
void dispose() {
emailController.dispose();
fullNameController.dispose();
passwordController.dispose();
confirmPasswordController.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/amazox_prime/features/auth/lib | mirrored_repositories/amazox_prime/features/auth/lib/components/sign_up_form.dart | import 'package:auth/auth.dart';
class SignUpForm extends StatefulWidget {
const SignUpForm({
required this.emailController,
required this.passwordController,
required this.confirmPasswordController,
required this.formKey,
required this.fullNameController,
super.key,
});
final TextEditingController emailController;
final TextEditingController passwordController;
final TextEditingController confirmPasswordController;
final TextEditingController fullNameController;
final GlobalKey<FormState> formKey;
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
bool obscurePassword = true;
bool obscureConfirmPassword = true;
@override
Widget build(BuildContext context) {
return Form(
key: widget.formKey,
child: Column(
children: <Widget>[
AppTextField(
controller: widget.fullNameController,
hintText: StringConstant.username,
keyboardType: TextInputType.name,
),
const SizedBox(
height: Dimensions.SIZE_20,
),
AppTextField(
controller: widget.emailController,
hintText: StringConstant.emailAddress,
keyboardType: TextInputType.emailAddress,
),
const SizedBox(
height: Dimensions.SIZE_20,
),
AppTextField(
controller: widget.passwordController,
hintText: StringConstant.password,
maxLines: Dimensions.SIZE_1.toInt(),
obscureText: obscurePassword,
keyboardType: TextInputType.visiblePassword,
suffixIcon: IconButton(
onPressed: () {
setState(() {
obscurePassword = !obscurePassword;
});
},
icon: Icon(
obscurePassword ? Icons.remove_red_eye : Icons.hide_source,
color: ApplicationColors.disabledColor,
),
),
),
const SizedBox(
height: Dimensions.SIZE_20,
),
AppTextField(
maxLines: Dimensions.SIZE_1.toInt(),
controller: widget.confirmPasswordController,
hintText: StringConstant.confirmPassword,
obscureText: obscureConfirmPassword,
keyboardType: TextInputType.visiblePassword,
suffixIcon: IconButton(
onPressed: () {
setState(() {
obscureConfirmPassword = !obscureConfirmPassword;
});
},
icon: Icon(
obscureConfirmPassword
? Icons.remove_red_eye
: Icons.hide_source,
color: ApplicationColors.disabledColor,
),
),
validator: (String? value) {
if (value != widget.passwordController.text) {
return StringConstant.passwordsNotMatch;
}
return null;
},
),
],
),
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.