diff --git a/lib/comments/screens/add_comment_screen.dart b/lib/comments/screens/add_comment_screen.dart index 16ae09ff..f1020e2c 100644 --- a/lib/comments/screens/add_comment_screen.dart +++ b/lib/comments/screens/add_comment_screen.dart @@ -15,9 +15,6 @@ class _AddCommentScreenState extends State { TextEditingController controller = TextEditingController(); @override void didChangeDependencies() { - // TODO: implement didChangeDependencies - //===============================Fetch subreddit data =======================================// - var temp = ModalRoute.of(context)?.settings.arguments as Map; parentId = temp['parentId']; @@ -27,9 +24,7 @@ class _AddCommentScreenState extends State { createComment(String text) async { if (await Provider.of(context, listen: false) - .postComment(parentId, 'Post', text)) { - print('created comment'); - } + .postComment(parentId, 'Post', text)) {} } @override @@ -37,7 +32,7 @@ class _AddCommentScreenState extends State { return Scaffold( appBar: AppBar( leading: IconButton( - icon: Icon( + icon: const Icon( Icons.close, size: 20, ), @@ -45,7 +40,7 @@ class _AddCommentScreenState extends State { Navigator.pop(context); }, ), - title: Text( + title: const Text( "Add a comment", style: TextStyle(fontSize: 20, color: Colors.black), ), @@ -57,7 +52,7 @@ class _AddCommentScreenState extends State { Navigator.pop(context); } : null, - child: Text( + child: const Text( "Post", style: TextStyle( color: Colors.blue, @@ -67,11 +62,11 @@ class _AddCommentScreenState extends State { ], ), body: Padding( - padding: EdgeInsetsDirectional.all(10), + padding: const EdgeInsetsDirectional.all(10), child: Column( children: [ Text(title), - Divider( + const Divider( height: 10, ), Expanded( diff --git a/lib/comments/screens/add_reply_screen.dart b/lib/comments/screens/add_reply_screen.dart index 2d69cd5c..b737df6a 100644 --- a/lib/comments/screens/add_reply_screen.dart +++ b/lib/comments/screens/add_reply_screen.dart @@ -37,9 +37,6 @@ class _AddReplyScreenState extends State { @override void didChangeDependencies() { - // TODO: implement didChangeDependencies - //===============================Fetch subreddit data =======================================// - var temp = ModalRoute.of(context)?.settings.arguments as Map; parentId = temp['parentId']; @@ -52,9 +49,7 @@ class _AddReplyScreenState extends State { createComment(String text) async { if (await Provider.of(context, listen: false) - .postComment(parentId, 'Comment', text)) { - print('created comment'); - } + .postComment(parentId, 'Comment', text)) {} } @override @@ -62,7 +57,7 @@ class _AddReplyScreenState extends State { return Scaffold( appBar: AppBar( leading: IconButton( - icon: Icon( + icon: const Icon( Icons.close, size: 20, ), @@ -70,7 +65,7 @@ class _AddReplyScreenState extends State { Navigator.pop(context); }, ), - title: Text( + title: const Text( "Reply", style: TextStyle(fontSize: 20, color: Colors.black), ), @@ -82,7 +77,7 @@ class _AddReplyScreenState extends State { Navigator.pop(context); } : null, - child: Text( + child: const Text( "Post", style: TextStyle( color: Colors.blue, @@ -92,7 +87,7 @@ class _AddReplyScreenState extends State { ], ), body: Padding( - padding: EdgeInsetsDirectional.all(10), + padding: const EdgeInsetsDirectional.all(10), child: Column( children: [ Row( @@ -125,11 +120,11 @@ class _AddReplyScreenState extends State { ), ], ), - SizedBox( + const SizedBox( height: 10, ), Text(comment), - Divider( + const Divider( height: 10, ), Expanded( diff --git a/lib/comments/widgets/comment.dart b/lib/comments/widgets/comment.dart index f42776fc..ee627a82 100644 --- a/lib/comments/widgets/comment.dart +++ b/lib/comments/widgets/comment.dart @@ -4,9 +4,16 @@ import '../models/comment_model.dart'; import 'comment_body.dart'; import 'comment_header.dart'; +/// A widget to display a comment in tree + class Comment extends StatefulWidget { + /// The data of the commment final CommentModel data; + + /// The userName final String userName; + + /// The level of comment final int level; const Comment( {super.key, required this.data, required this.userName, this.level = 0}); @@ -20,7 +27,7 @@ class _CommentState extends State { @override Widget build(BuildContext context) { return widget.data.type != null - ? Text('more comments') + ? const Text('more comments') : Container( margin: EdgeInsets.only(bottom: widget.level != 0 ? 0 : 10), child: Material( @@ -61,8 +68,8 @@ class _CommentState extends State { text: widget.data.text ?? '', ), CommentFooter( - commentVoteStatus: 1, - votes: 20, + commentVoteStatus: 0, + votes: widget.data.votes ?? 0, data: widget.data, ) ], @@ -87,7 +94,7 @@ class _CommentState extends State { level: widget.level + 1, )) .toList()) - : SizedBox() + : const SizedBox() ]), ), ); diff --git a/lib/comments/widgets/comment_footer.dart b/lib/comments/widgets/comment_footer.dart index 34df3f45..57dbbc42 100644 --- a/lib/comments/widgets/comment_footer.dart +++ b/lib/comments/widgets/comment_footer.dart @@ -27,64 +27,6 @@ class _CommentFooterState extends State { int commentVoteStatus; int votes; _CommentFooterState(this.commentVoteStatus, this.votes); -// upVote() async { -// if (postVoteStatus != 1) { -// if (await Provider.of(context, listen: false) -// .updateVotes(widget.id, 1)) { -// setState(() { -// if (postVoteStatus == -1) { -// votes = votes + 2; -// widget.data.votes = (widget.data.votes! + 2); -// } else { -// ++votes; -// widget.data.votes = (widget.data.votes! + 1); -// } -// postVoteStatus = 1; -// widget.data.postVoteStatus = 1.toString(); -// }); -// } -// } else { -// if (await Provider.of(context, listen: false) -// .updateVotes(widget.id, 0)) { -// setState(() { -// postVoteStatus = 0; -// widget.data.postVoteStatus = 0.toString(); -// widget.data.votes = (widget.data.votes! - 1); -// --votes; -// }); -// } -// } -// } - -// downVote() async { -// if (postVoteStatus != -1) { -// if (await Provider.of(context, listen: false) -// .updateVotes(widget.id, -1)) { -// setState(() { -// if (postVoteStatus == 1) { -// votes = votes - 2; -// widget.data.votes = (widget.data.votes! - 2); -// } else { -// --votes; -// widget.data.votes = (widget.data.votes! - 1); -// } -// postVoteStatus = -1; -// widget.data.postVoteStatus = (-1).toString(); -// }); -// } -// } else { -// if (await Provider.of(context, listen: false) -// .updateVotes(widget.id, 0)) { -// setState(() { -// postVoteStatus = 0; -// widget.data.postVoteStatus = 0.toString(); - -// ++votes; -// widget.data.votes = (widget.data.votes! + 1); -// }); -// } -// } -// } upVote() {} downVote() {} @@ -92,21 +34,17 @@ class _CommentFooterState extends State { @override Widget build(BuildContext context) { return Container( - margin: EdgeInsetsDirectional.only(start: 10, end: 10), + margin: const EdgeInsetsDirectional.only(start: 10, end: 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - CommentPopUpMenu(isSaved: true), + const CommentPopUpMenu(isSaved: true), const SizedBox( width: 20, ), InkWell( onTap: () { - print(widget.data.sId); - print(widget.data.text); - print(widget.data.author?.userName); - print(widget.data.createdAt); - Get.to(AddReplyScreen(), arguments: { + Get.to(const AddReplyScreen(), arguments: { 'parentId': widget.data.sId, 'comment': widget.data.text, 'authorName': widget.data.author?.userName, @@ -138,7 +76,7 @@ class _CommentFooterState extends State { child: Tooltip( message: 'Upvote', child: Container( - padding: EdgeInsetsDirectional.all(8), + padding: const EdgeInsetsDirectional.all(8), child: (commentVoteStatus != 1) ? Icon( Typicons.up_outline, @@ -164,7 +102,7 @@ class _CommentFooterState extends State { child: Tooltip( message: 'Downvote', child: Container( - padding: EdgeInsetsDirectional.all(8), + padding: const EdgeInsetsDirectional.all(8), child: (commentVoteStatus != -1) ? Icon( Typicons.down_outline, diff --git a/lib/comments/widgets/comment_popup_menu.dart b/lib/comments/widgets/comment_popup_menu.dart index bc96b074..50be1330 100644 --- a/lib/comments/widgets/comment_popup_menu.dart +++ b/lib/comments/widgets/comment_popup_menu.dart @@ -55,7 +55,7 @@ class CommentPopUpMenu extends StatelessWidget { children: [ Container( margin: const EdgeInsetsDirectional.only(end: 5), - child: Icon(Icons.share_outlined), + child: const Icon(Icons.share_outlined), ), Text( 'Share', diff --git a/lib/comments/widgets/comments_list.dart b/lib/comments/widgets/comments_list.dart index 6fe194c7..6c1d63d2 100644 --- a/lib/comments/widgets/comments_list.dart +++ b/lib/comments/widgets/comments_list.dart @@ -6,8 +6,15 @@ import '../models/comment_model.dart'; import '../providers/comments_provider.dart'; import 'comment.dart'; +/// This widget displays the comments tree of a post + class CommentsList extends StatefulWidget { + /// The ID of the post to get its comments + final String postId; + + /// The user name + final String userName; const CommentsList({super.key, required this.postId, required this.userName}); diff --git a/lib/comments/widgets/view_comment.dart b/lib/comments/widgets/view_comment.dart index 21fcd198..e22c0c92 100644 --- a/lib/comments/widgets/view_comment.dart +++ b/lib/comments/widgets/view_comment.dart @@ -13,12 +13,12 @@ class _ViewCommentState extends State { Widget build(BuildContext context) { return Container( height: 50, - margin: EdgeInsetsDirectional.only(start: 10), + margin: const EdgeInsetsDirectional.only(start: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (int i = 0; i < widget.level; i++) - VerticalDivider( + const VerticalDivider( color: Colors.grey, thickness: 2, ), diff --git a/lib/createpost/controllers/posts_controllers.dart b/lib/createpost/controllers/posts_controllers.dart index 3f7c3857..ee03ba31 100644 --- a/lib/createpost/controllers/posts_controllers.dart +++ b/lib/createpost/controllers/posts_controllers.dart @@ -1,4 +1,5 @@ import 'dart:io'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; @@ -18,21 +19,21 @@ class PostController extends GetxController { List moderatedSubreddits = [].obs; RxString subredditToSubmitPost = "".obs; - RxString iconOfSubredditToSubmittPost = "".obs; - RxString idOfSubredditToSubmittPost = "".obs; - RxBool showMore = false.obs; + RxString iconOfSubredditToSubmittPost="".obs; + RxString idOfSubredditToSubmittPost="".obs; + RxBool showMore=false.obs; RxBool isPostSpoiler = false.obs; RxBool isPostNSFW = false.obs; RxBool isLoading = true.obs; final services = PostServices(); Rx postTitle = TextEditingController().obs; - Rx textPost = quill.QuillController.basic().obs; + Rx textPost=quill.QuillController.basic().obs; Rx urlPost = TextEditingController().obs; RxString typeOfPost = ''.obs; GlobalKey formKey = GlobalKey(); GlobalKey formKeyUrl = GlobalKey(); - List? imageFileList = [].obs; + List? imageFileList = [].obs; Future? initializeVideoPlayerFuture; @@ -40,23 +41,22 @@ class PostController extends GetxController { final videoFile = Rx(null); final videoController = Rx(null); //Flairs belonging to subreddit - List flairsOfSubreddit = [].obs; - RxString idOfFlair = "".obs; - RxString textOfFlair = "".obs; - RxString textColorOfFlair = "None".obs; - RxString backgroundColorOfFlair = "None".obs; - RxBool isSubredditHasFlair = false.obs; - RxBool isFromHomeDirect = true.obs; - List checking = [].obs; - RxInt checkFromWhich = 0.obs; + ListflairsOfSubreddit=[].obs; + RxString idOfFlair="".obs; + RxString textOfFlair="".obs; + RxString textColorOfFlair="None".obs; + RxString backgroundColorOfFlair="None".obs; + RxBool isSubredditHasFlair=false.obs; + RxBool isFromHomeDirect=true.obs; + Listchecking=[].obs; + RxInt checkFromWhich=0.obs; dynamic argumentData = Get.arguments; @override - void onInit() { - _fetchHouses(); + void onInit() + { getSubreddits(); super.onInit(); } - // @override // onClose() // { @@ -64,33 +64,32 @@ class PostController extends GetxController { // typeOfPost.value=''; // super.onClose(); // } - getFlairsOfSubreddit() async { + getFlairsOfSubreddit() async{ final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); - try { + try{ print('/subreddit/${subredditToSubmitPost}/flairs'); - await DioClient.get(path: '/subreddits/${subredditToSubmitPost}/flair') - .then((value) { + await DioClient.get(path:'/subreddits/${subredditToSubmitPost}/flair').then((value){ print("Flairs returned are $value"); - value.data['data'].forEach((val) { + value.data['data'].forEach((val) + { flairsOfSubreddit.add(FlairModel.fromJson(val)); }); }); - checking = List.filled(flairsOfSubreddit.length + 1, false); - print( - "the size of returned list of flairs of subreddit is ${flairsOfSubreddit.length}"); + checking = List.filled(flairsOfSubreddit.length+1, false); + print("the size of returned list of flairs of subreddit is ${flairsOfSubreddit.length}"); print("the size of checking list is ${checking.length}"); - } catch (e) { - print( - "error in fetching the flairs of ${subredditToSubmitPost} subreddit -> $e"); } - } + catch(e){ + print("error in fetching the flairs of ${subredditToSubmitPost} subreddit -> $e"); + } + } getSubreddits() async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - await DioClient.get(path: '$mySubreddits/subscriber').then((value) { + await DioClient.get(path:'$mySubreddits/subscriber').then((value) { print("subs list $value"); value.data['data'].forEach((value1) { subscribedSubreddits.add(userSubredditsResponse.fromJson(value1)); @@ -98,7 +97,7 @@ class PostController extends GetxController { }); }); - await DioClient.get(path: '$mySubreddits/moderator').then((value) { + await DioClient.get(path:'$mySubreddits/moderator').then((value) { print("moderator list $value"); value.data['data'].forEach((value1) { moderatedSubreddits.add(userSubredditsResponse.fromJson(value1)); @@ -111,66 +110,73 @@ class PostController extends GetxController { print("error in fething subreddits of user $error"); } } - - sendPost(BuildContext context) async { + Future sendPost(BuildContext context, {required String title,required String text,required String kind ,required String url,required String owner,required String ownerType,required bool nsfw,required bool spoiler}) async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); - var response; + var response ; try { - response = await DioClient.post(path: "/posts", data: { - "title": "AHMED", - //postTitle.value.text , - "kind": typeOfPost.value as String, - "text": "KKKK", - //(DeltaToHTML.encodeJson(textPost.value.document.toDelta().toJson())) as String, - //"url":urlPost.value.text as String , - "owner": idOfSubredditToSubmittPost.value as String, - "ownerType": - (subredditToSubmitPost.value == "Myprofile") ? "User" : "Subreddit", - // "nsfw": isPostNSFW.value , - // "spoiler": isPostSpoiler.value , + response= await DioClient.post(path: "/posts", data:{ + "title": title , + "kind": kind, + "text":text, + "url":url, + "owner":owner, + "ownerType": ownerType, + "nsfw": nsfw , + "spoiler": spoiler , "sendReplies": true, - - // "flairId":idOfFlair.value as String , - // "flairText":textOfFlair.value as String, - - // "title": "post", - // "kind": "self", - // "text": "Test comment count", - // "owner": "63a193ffe3d2b7ad4a939978", - // "ownerType": "User", - // "nsfw": false, - // "spoiler": true, - // "sendReplies": true + "suggestedSort":"hot" }); - print("YA RAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB"); if (response.statusCode == 200 || response.statusCode == 201) { - print("response of sending post ${response.data}"); ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + const SnackBar( content: Text("sent successfuly", style: TextStyle(color: Colors.white)), backgroundColor: Colors.green), ); - print(response.statusCode); - print("the id of post created ${response.data["data"]["_id"]}"); - //print(json.decode(response.data)['message']); } - // return response.data["data"]["_id"]; + return response.data["data"]["_id"]; } catch (e) { print("error in sending the post -> $e"); - // return 0; + return ""; } } - - Future _fetchHouses() async { + Future sendPostWithFlair(BuildContext context, {required String title,required String text,required String kind ,required String url,required String owner,required String ownerType,required bool nsfw,required bool spoiler,required String textFlair,required String idFlair}) async { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + var response ; try { - ///here fitch Your Posts - } finally { - isLoading(false); + response = await DioClient.post(path: "/posts", data: { + "title": title, + "kind": kind, + "text": text, + "url": url, + "owner": owner, + "ownerType": ownerType, + "nsfw": nsfw, + "spoiler": spoiler, + "sendReplies": true, + "flairId": idOfFlair, + "flairText": textOfFlair, + "suggestedSort":"hot" + }); + if (response.statusCode == 200 || response.statusCode == 201) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text("sent successfuly", + style: TextStyle(color: Colors.white)), + backgroundColor: Colors.green), + ); + } + return response.data["data"]["_id"]; + } + catch (e) { + print("error in sending the post -> $e"); + return ""; } } + Future createPost() async { try { isLoading.value = true; @@ -183,10 +189,9 @@ class PostController extends GetxController { isLoading(false); } } - Future getVideo() async { Future videoFiles = - ImagePicker().pickVideo(source: ImageSource.gallery); + ImagePicker().pickVideo(source: ImageSource.gallery); videoFiles.then((file) async { videoFile.value = File(file!.path); videoController.value = VideoPlayerController.file(videoFile.value!); @@ -219,4 +224,6 @@ class PostController extends GetxController { typeOfPost.close(); super.dispose(); } + + } diff --git a/lib/createpost/screens/createpost.dart b/lib/createpost/screens/createpost.dart index 38e8b99c..8a829e6e 100644 --- a/lib/createpost/screens/createpost.dart +++ b/lib/createpost/screens/createpost.dart @@ -1,22 +1,33 @@ ///////////////////////BY ME/////////////////////////////////////////// import 'dart:convert'; +import 'dart:io'; import 'package:post/delta_to_html.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; -// import 'package:post/discover/discover.dart'; +import 'package:multi_image_picker/multi_image_picker.dart'; import 'package:post/home/screens/home_layout.dart'; import 'dart:async'; +import '../../home/controller/home_controller.dart'; +import '../../home/widgets/community_container.dart'; +import '../../home/widgets/custom_upper_bar.dart'; import '../../icons/icon_broken.dart'; import '../controllers/posts_controllers.dart'; import '../screens/posttocommunity.dart'; import '../widgets/type_of_post.dart'; +import '../widgets/type_of_post_web.dart'; import 'finalpost.dart'; + + import 'package:flutter_quill/flutter_quill.dart' as quill; + class CreatePostSCreen extends StatefulWidget { + // const CreatePostSCreen({ // Key? key, // this.name="", @@ -26,443 +37,756 @@ class CreatePostSCreen extends StatefulWidget { // final String name; @override State createState() => _CreatePostSCreenState(); + } class _CreatePostSCreenState extends State { // const CreatePostSCreen({super.key}); final ImagePicker imagePicker = ImagePicker(); final ImagePicker videoPicker = ImagePicker(); - final PostController controller = Get.put(PostController(), permanent: false); - + final PostController controller = Get.put( + PostController(),permanent: false + ); + final HomeController controllerForHome = Get.put( + HomeController(),permanent: false + ); Future? initializeVideoPlayerFuture; @override - void initState() { + void initState() + { + // TODO: implement initState - if (Get.arguments[0] == 0) { - controller.isFromHomeDirect.value = true; - } else { - controller.isFromHomeDirect.value = false; - controller.iconOfSubredditToSubmittPost.value = Get.arguments[1]; - controller.subredditToSubmitPost.value = Get.arguments[2]; + if(Get.arguments[0]==0) + { + controller.isFromHomeDirect.value=true; + } + else + { + controller.isFromHomeDirect.value=false; + controller.iconOfSubredditToSubmittPost.value=Get.arguments[1] ; + controller.subredditToSubmitPost.value=Get.arguments[2] ; } super.initState(); } @override Widget build(BuildContext context) { - return Obx( - () => WillPopScope( - onWillPop: () async { - final value = (controller.imageFileList!.length > 0 || - controller.videoFile.value != null || - controller.urlPost.value.text != "") - ? await showDialog( - context: context, - builder: (context) { - return AlertDialog( - content: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - ), - width: MediaQuery.of(context).size.width / 0.001, - height: MediaQuery.of(context).size.height / 10, - child: (Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - 'Discard Post Submission?', - style: TextStyle( - fontSize: 17, fontWeight: FontWeight.w500), - ), - SizedBox( - height: 10, - ), - Row( - children: [ - Expanded( - child: ElevatedButton( - onPressed: () { - Get.back(); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[200], - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(30), - ), - ), - child: const Text( - 'Cancel', - style: TextStyle( - color: Colors.grey, - fontWeight: FontWeight.w600, - ), - ), + double ScreenSizeWidth = MediaQuery.of(context).size.width; + + final isDesktop = ScreenSizeWidth >= 700; + final isMobile = ScreenSizeWidth < 700; + if (isDesktop){ + return Obx(()=> + Scaffold( + backgroundColor: const Color(0xA2D4E4FA), + appBar: PreferredSize( preferredSize: Size(700, 60),child: UpBar(controller: controllerForHome, controllerForCreatePost: controller,)), + body:SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + SizedBox(height: 70,), + Padding( + padding: const EdgeInsetsDirectional.only(end: 600.0), + child: Text("Create a Post",style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),), + ), + SizedBox(height: 10,), + Padding( + padding: const EdgeInsetsDirectional.only(end: 600.0), + child: Container( + width: 300, + height: 50, + color: Colors.white, + child:PopupMenuButton( + + child: Row( + children: [ + // Icon(Icons.home_filled), + SizedBox(width: 20,), + Text("choose a community"), + SizedBox(width: 80,), + Icon(Icons.arrow_drop_down_sharp) + ], + ), + elevation: 0, + color: Colors.white, + offset:Offset(0,35) , + itemBuilder: (context)=>[ + PopupMenuItem( + value:1, + child: Container( + width: 300, + child: Column( + children:List.generate(controller.moderatedSubreddits.length, (index) => CommunityContainer(nameOfSubreddit: controller.moderatedSubreddits[index].subredditName!, iconOfSubreddit: controller.moderatedSubreddits[index].icon!)) ), - ), - SizedBox( - width: 5, - ), - Expanded( - child: ElevatedButton( - onPressed: () { - controller.textPost.value.clear(); - controller.postTitle.value.clear(); - controller.imageFileList!.clear(); - controller.videoFile.value = null; - controller.videoController.value = null; - controller.urlPost.value.clear(); - Get.to(HomeLayoutScreen()); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.red[700], - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(30), - ), - ), - child: const Text( - 'Discard', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.w600, - ), - ), + ) + + ), + PopupMenuItem( + value:2, + child: Container( + width: 300, + child: Column( + children:List.generate(controller.subscribedSubreddits.length, (index) => CommunityContainer(nameOfSubreddit: controller.subscribedSubreddits[index].subredditName!, iconOfSubreddit: controller.subscribedSubreddits[index].icon!)) ), - ), - ], - ) + ) + + ), ], - ))), - ); - }) - : null; - - if (value != null) { - return Future.value(value); - } else { - return Future.value(true); - } - }, - child: Scaffold( - backgroundColor: Colors.white, - body: Form( - key: controller.formKey, - child: Column( - children: [ - const SizedBox(height: 40.0), - Row( - children: [ - IconButton( - onPressed: () { - // Get.delete(); - Get.back(); - }, - color: Colors.black45, - icon: Icon( - Icons.close, - size: 32.0, + ) ), ), - const Spacer(), + SizedBox(height: 20,), Padding( - padding: const EdgeInsetsDirectional.only(end: 20.0), - child: controller.isLoading.value - ? const CircularProgressIndicator( - color: Colors.blue, - ) - : MaterialButton( - onPressed: () { - if (controller.formKeyUrl.currentState! - .validate() && - controller.postTitle.value.text != "") { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Processing Data')), - ); - if (controller.isFromHomeDirect.value == - true) { - Get.to(BuildSubreddit()); - } else { - Get.to(FinalPost()); - } - } - }, - elevation: 0.0, - height: 35.0, - minWidth: 80.0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0)), - color: controller.postTitle.value.text == "" - ? Colors.grey[100] - : Colors.blue[900], - child: Text( - "Next", - style: TextStyle( - color: Colors.grey[400], + padding: const EdgeInsetsDirectional.only(start: 150), + child: Row( + children: [ + + InkWell( + onTap: (){ + controller.typeOfPost.value = "self"; + controller.typeOfPost.update((val) { }); + + }, + child: Container( + padding: EdgeInsetsDirectional.only(start: 10), + height: 50, + width: 100, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all(color: Colors.black,width: 0.5) + ), + child: Center( + + child: Row( + children: [ + Icon( + Icons.post_add, + color: Colors.black, + ), + const SizedBox(width: 3,), + Text( + "Post", + style: TextStyle( + color: Colors.black + ) + ) + ], ), ), ), - ), - ], - ), - SizedBox( - height: 10, - ), - Visibility( - visible: !controller.isFromHomeDirect.value, - child: Padding( - padding: const EdgeInsetsDirectional.only(start: 14), - child: Row( - children: [ - GestureDetector( - onTap: () { - Get.to(BuildSubreddit()); - }, - child: Row( - children: [ - CircleAvatar( - backgroundImage: NetworkImage( - '${controller.iconOfSubredditToSubmittPost}'), - radius: 16.0, - ), - SizedBox( - width: 4.0, + ), + InkWell( + onTap: (){ + controller.imageFileList!.clear(); + selectImages(); + print( + "lenght of list is ${controller.imageFileList!.length}"); + controller.typeOfPost.value = "image"; + }, + child: Container( + padding: EdgeInsetsDirectional.only(start: 10), + height: 50, + width: 180, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all(color: Colors.black,width: 0.5) ), - ElevatedButton.icon( - onPressed: () { - Get.to(BuildSubreddit()); - }, - icon: Text( - controller.subredditToSubmitPost.value, - style: const TextStyle(color: Colors.black), + child: Center( + + child: Row( + children: [ + Icon( + Icons.camera_alt, + color: Colors.black, + ), + const SizedBox(width: 3,), + Text( + "Images ", + style: TextStyle( + color: Colors.black + ) + ) + ], ), - label: const Icon( - IconBroken.Arrow___Down_2, - color: Colors.black, - size: 15, + ), + ), + ), + InkWell( + onTap: (){ + controller.videoFile.value=null; + controller.videoController.value=null; + controller.getVideo(); + controller.typeOfPost.value = "video"; + }, + child: Container( + padding: EdgeInsetsDirectional.only(start: 10), + height: 50, + width: 180, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all(color: Colors.black,width: 0.5) + ), + child: Center( + + child: Row( + children: [ + Icon( + Icons.video_camera_back_outlined, + color: Colors.black, + ), + const SizedBox(width: 3,), + Text( + "Video", + style: TextStyle( + color: Colors.black + ) + ) + ], ), - style: ButtonStyle( - elevation: - MaterialStateProperty.all(0), - backgroundColor: - MaterialStateProperty.all(Colors.white), + ), + ), + ), + InkWell( + onTap: (){ + controller.typeOfPost.value = "link"; + controller.typeOfPost.update((val) { }); + }, + child: Container( + padding: EdgeInsetsDirectional.only(start: 10), + height: 50, + width: 100, + decoration: BoxDecoration( + color: Colors.white, + border: Border.all(color: Colors.black,width: 0.5) + ), + child: Center( + + child: Row( + children: [ + Icon( + Icons.link, + color: Colors.black, + ), + const SizedBox(width: 3,), + Text( + "Link", + style: TextStyle( + color: Colors.black + ) + ) + ], ), ), - ], + ), ), - ), - const Spacer(), - TextButton( - onPressed: () => showModalBottomSheet( - context: context, - builder: (context) => Center( - child: Column( - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - const Expanded( - child: Center( - child: Text( - "Community Standards"))), - ElevatedButton( - style: ButtonStyle( - backgroundColor: - MaterialStateProperty.all( - Colors.blue[900], - ), - ), - onPressed: () { - Navigator.pop(context); - }, - child: Text( - "understand", - style: TextStyle( - color: Colors.white, - ), - ), - ) - ], - ), - )), - child: const Text( - "Rules", - style: TextStyle(color: Colors.blue), - )) - ], + + ], + ), ), - ), - ), - const SizedBox( - height: 10, - ), - Padding( - padding: const EdgeInsetsDirectional.only(start: 10.0), - child: TextFormField( - onChanged: (value) { - controller.postTitle.refresh(); - }, - validator: ((value) { - if (value == null || value.isEmpty) { - return 'Please enter some text'; - } - return null; - }), - controller: controller.postTitle.value, - enabled: true, - style: const TextStyle( - fontSize: 20.0, fontWeight: FontWeight.w700), - showCursor: true, - cursorColor: Colors.blue, - cursorHeight: 20.0, - textAlign: TextAlign.start, - decoration: const InputDecoration( - hintText: "An interesting title", - border: InputBorder.none), - ), - ), - const SizedBox( - height: 10.0, - ), - const SizedBox( - height: 10.0, - ), - Expanded( - child: BuildFormType( - controller: controller, - )), - MaterialButton( - child: Text("press"), - onPressed: () { - print(controller.textPost.value.document - .toDelta() - .toJson()); - print( - "==============================================================="); - print((DeltaToHTML.encodeJson(controller - .textPost.value.document - .toDelta() - .toJson()))); - print((jsonEncode(controller.textPost.value.document - .toDelta() - .toJson())) - .toString() - .runtimeType); - print(controller.textPost.value.getPlainText); - print(controller.textPost.value.getPlainText()); - print(controller.textPost.value.document.toPlainText()); - print(controller.textPost.value.document); - print(controller.urlPost.value.text); - print(controller.textPost.value.document - .toPlainText() - .runtimeType); - print(controller.textPost.value.document.runtimeType); - print(controller.textPost.value.runtimeType); - }), - Padding( - padding: - const EdgeInsetsDirectional.only(start: 20, bottom: 10), - child: Row( - children: [ - IconButton( - onPressed: () { - controller.typeOfPost.value = "self"; - }, - icon: const Icon(IconBroken.Document), + SizedBox(height: 10,), + Container( + width: 1000, + height: 50, + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.white, ), - IconButton( - onPressed: () async { - controller.imageFileList!.clear(); - selectImages(); - print( - "lenght of list is ${controller.imageFileList!.length}"); - controller.typeOfPost.value = "image"; - }, - icon: const Icon(IconBroken.Image_2)), - IconButton( - onPressed: () { - controller.videoFile.value = null; - controller.videoController.value = null; - controller.getVideo(); - controller.typeOfPost.value = "video"; + + child:TextFormField( + onChanged: (value) { + controller.postTitle.refresh(); }, - icon: const Icon(IconBroken.Video), + validator: ((value) { + if (value == null || value.isEmpty) { + return 'Please enter some text'; + } + return null; + }), + controller: controller.postTitle.value, + enabled: true, + style: const TextStyle( + fontSize: 20.0, fontWeight: FontWeight.w700), + showCursor: true, + cursorColor: Colors.blue, + cursorHeight: 20.0, + textAlign: TextAlign.start, + decoration: const InputDecoration( + hintText: "Title", + border:OutlineInputBorder( + borderSide: BorderSide(width: 20,color: Colors.black) + )), ), - IconButton( - onPressed: () { - controller.typeOfPost.value = "link"; - }, - icon: const Icon(IconBroken.Bookmark), + ), + SizedBox(height: 20,), + BuildFormTypeWeb(controller:controller), + SizedBox(height: 10,), + Padding( + padding: const EdgeInsetsDirectional.only(start: 20.0), + child: Row( + children: [ + /// Spoiler + InkWell( + onTap: (){ + if (controller.isPostSpoiler.value == false) { + controller.isPostSpoiler.value = true; + controller.isPostSpoiler.refresh(); + } else { + controller.isPostSpoiler.value = false; + controller.isPostSpoiler.refresh(); + } + + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 5), + decoration: BoxDecoration( + color:(controller.isPostSpoiler.value==true)? Colors.red:Colors.white, + borderRadius: BorderRadius.circular(30), + border: Border.all( + color: Colors.grey + ) + ), + child: Row( + children: [ + Icon(Icons.add, + color: Colors.black, + size: 20,), + const SizedBox(width: 5,), + Text( + "Spoiler", + style:TextStyle(color: Colors.black) + ) + ], + ), + ), + ), + const SizedBox(width: 5,), + /// NSFW + InkWell( + onTap: (){ + if (controller.isPostNSFW.value == false) { + controller.isPostNSFW.value = true; + controller.isPostNSFW.refresh(); + } else { + controller.isPostNSFW.value = false; + controller.isPostNSFW.refresh(); + } + }, + + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 5), + decoration: BoxDecoration( + color:(controller.isPostNSFW.value==true)? Colors.red:Colors.white, + borderRadius: BorderRadius.circular(30), + border: Border.all( + color: Colors.black + ) + ), + child: Row( + children: const [ + Icon(Icons.add, + color: Colors.black,size: 20,), + SizedBox(width: 5,), + Text( + "NSFW", + style: TextStyle(color: Colors.black), + ) + ], + ), + ), + ), + const SizedBox(width: 700,), + InkWell( + onTap: (){ + if(controller.postTitle.value.text!=""&&controller.formKeyUrl.currentState!.validate()) + { + controller.sendPost(context, + title: controller.postTitle.value.text, + text: (DeltaToHTML.encodeJson(controller.textPost.value.document.toDelta().toJson())).toString(), + kind: controller.typeOfPost.value, + url: controller.urlPost.value.text, + owner: (controller.idOfSubredditToSubmittPost.value), + ownerType:"Subreddit" , + nsfw: controller.isPostNSFW.value, + spoiler: controller.isPostSpoiler.value, + ); + controller.postTitle.value.clear(); + controller.urlPost.value.clear(); + controller.textPost.value.clear(); + controller.isPostSpoiler.value=false; + controller.isPostNSFW.value=false; + // Navigator.pop(context); + Get.to(HomeLayoutScreen()); + } + else return; + }, + + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 5), + decoration: BoxDecoration( + color:(controller.postTitle.value.text=="")? Colors.white:Colors.blue, + borderRadius: BorderRadius.circular(30), + border: Border.all( + color: Colors.black + ) + ), + child: Row( + children: const [ + SizedBox(width: 5,), + Text( + "Post", + style: TextStyle(color: Colors.black), + ) + ], + ), + ), + ), + ], ), - ], - ), - ), - const SizedBox( - height: 10.0, - ), - const SizedBox( - height: 10.0, + ), + SizedBox(height: 100,) + ], ), - Expanded( - child: BuildFormType( - controller: controller, - )), - Padding( - padding: - const EdgeInsetsDirectional.only(start: 20, bottom: 10), - child: Row( + ) + ), + ); + } + return Obx(()=> + WillPopScope( + onWillPop: () async { + final value = ( controller.imageFileList!.length>0 || controller.videoFile.value != null || controller.urlPost.value.text != "")?await + showDialog(context: context, + builder: (context) + { + return AlertDialog( + content: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + ), + width: MediaQuery + .of(context) + .size + .width / 0.001, + height: MediaQuery + .of(context) + .size + .height / 10, + child: ( + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Discard Post Submission?', + style: TextStyle( + fontSize: 17, fontWeight: FontWeight.w500), + ), + SizedBox(height: 10,), + Row( + children: [ + Expanded( + child: ElevatedButton( + onPressed: () { + Get.back(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.grey[200], + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + 30), + ), + ), + child: + const Text( + 'Cancel', + style: TextStyle( + color: Colors.grey, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + SizedBox(width: 5,), + Expanded( + child: ElevatedButton( + onPressed: () { + controller.textPost.value.clear(); + controller.postTitle.value.clear(); + controller.imageFileList!.clear(); + controller.videoFile.value=null; + controller.videoController.value=null; + controller.urlPost.value.clear(); + Get.to(HomeLayoutScreen()); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red[700], + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + 30), + ), + ), + child: + const Text( + 'Discard', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ) + ], + ) + ) + ), + ); + } + ) : null ; + + if (value!=null) + { + return Future.value(value); + }else + { + return Future.value(true); + } + }, + child: Scaffold( + backgroundColor: Colors.white, + body: Form( + key: controller.formKey, + child: Column( + children: [ + const SizedBox(height: 40.0), + Row( children: [ IconButton( onPressed: () { - controller.typeOfPost.value = "text"; + // Get.delete(); + Get.back(); }, - icon: const Icon(IconBroken.Document), + color: Colors.black45, icon: Icon( + Icons.close, + size: 32.0, ), - IconButton( - onPressed: () async { - controller.imageFileList!.clear(); - selectImages(); - print( - "lenght of list is ${controller.imageFileList!.length}"); - controller.typeOfPost.value = "image"; - }, - icon: const Icon(IconBroken.Image_2)), - IconButton( - onPressed: () { - controller.videoFile.value = null; - controller.videoController.value = null; - controller.getVideo(); - controller.typeOfPost.value = "video"; - }, - icon: const Icon(IconBroken.Video), ), - IconButton( - onPressed: () { - controller.typeOfPost.value = "url"; - }, - icon: const Icon(IconBroken.Bookmark), + const Spacer(), + Padding( + padding: const EdgeInsetsDirectional.only(end: 20.0), + child: controller.isLoading.value + ? const CircularProgressIndicator( + color: Colors.blue, + ) + : MaterialButton( + onPressed: () { + if ( controller.formKeyUrl.currentState!.validate() && controller.postTitle.value.text !="") { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Processing Data')), + ); + if(controller.isFromHomeDirect.value==true) + { + Get.to(BuildSubreddit()); + } + else + { + Get.to(FinalPost()); + } + } + }, + elevation: 0.0, + height: 35.0, + minWidth: 80.0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20.0)), + color: controller.postTitle.value.text == "" + ? Colors.grey[100] + : Colors.blue[900], + child: Text( + "Next", + style: TextStyle( + color: Colors.grey[400], + ), + ), + ), ), + ], ), - ), - ], + SizedBox(height: 10,), + Visibility( + visible: !controller.isFromHomeDirect.value, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 14), + child: Row( + children: [ + GestureDetector( + onTap: () + { + Get.to(BuildSubreddit()); + }, + child: Row( + children: [ + CircleAvatar( + backgroundImage: NetworkImage('${controller.iconOfSubredditToSubmittPost}'), + radius: 16.0, + ), + SizedBox( + width: 4.0, + ), + ElevatedButton.icon( + onPressed: () { + Get.to(BuildSubreddit()); + }, + icon: Text( + controller.subredditToSubmitPost.value, + style: const TextStyle(color: Colors.black), + ), + label: const Icon( + IconBroken.Arrow___Down_2, + color: Colors.black, + size: 15, + ), + style: ButtonStyle( + elevation: MaterialStateProperty.all(0), + backgroundColor: + MaterialStateProperty.all(Colors.white), + ), + ), + ], + ), + ), + const Spacer(), + TextButton( + onPressed: () => showModalBottomSheet( + context: context, + builder: (context) => Center( + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + const Expanded( + child: Center( + child: Text( + "Community Standards"))), + ElevatedButton( + style: ButtonStyle( + backgroundColor: + MaterialStateProperty.all( + Colors.blue[900], + ), + ), + onPressed: () { + Navigator.pop(context); + }, + child: Text( + "understand", + style: TextStyle( + color: Colors.white, + ), + ), + ) + ], + ), + )), + child: const Text( + "Rules", + style: TextStyle(color: Colors.blue), + )) + ], + ), + ), + ), + const SizedBox(height: 10,), + Padding( + padding: const EdgeInsetsDirectional.only(start: 10.0), + child: TextFormField( + onChanged: (value) { + controller.postTitle.refresh(); + }, + validator: ((value) { + if (value == null || value.isEmpty) { + return 'Please enter some text'; + } + return null; + }), + controller: controller.postTitle.value, + enabled: true, + style: const TextStyle( + fontSize: 20.0, fontWeight: FontWeight.w700), + showCursor: true, + cursorColor: Colors.blue, + cursorHeight: 20.0, + textAlign: TextAlign.start, + decoration: const InputDecoration( + hintText: "An interesting title", + border: InputBorder.none), + ), + ), + + const SizedBox( + height: 10.0, + ), + + const SizedBox( + height: 10.0, + ), + Expanded(child: BuildFormType(controller: controller,)), + Padding( + padding: const EdgeInsetsDirectional.only(start: 20, bottom: 10), + child: Row( + children: [ + IconButton( + onPressed: () { + controller.typeOfPost.value = "self"; + }, + icon: const Icon(IconBroken.Document), + ), + IconButton( + onPressed: () async { + controller.imageFileList!.clear(); + selectImages(); + print( + "lenght of list is ${controller.imageFileList!.length}"); + controller.typeOfPost.value = "image"; + }, + icon: const Icon(IconBroken.Image_2)), + IconButton( + onPressed: () { + controller.videoFile.value=null; + controller.videoController.value=null; + controller.getVideo(); + controller.typeOfPost.value = "video"; + }, + icon: const Icon(IconBroken.Video), + ), + IconButton( + onPressed: () { + controller.typeOfPost.value = "link"; + }, + icon: const Icon(IconBroken.Bookmark), + ), + ], + ), + ), + + + + ], + ), ), ), ), - ), ); } - @override void dispose() { // TODO: implement dispose Get.delete(); super.dispose(); } - void selectImages() async { - final List? selectedImages = await imagePicker.pickMultiImage(); + final List? selectedImages = (await imagePicker.pickMultiImage()).cast(); if (selectedImages!.isNotEmpty) { controller.imageFileList!.addAll(selectedImages); } diff --git a/lib/createpost/screens/finalpost.dart b/lib/createpost/screens/finalpost.dart index e1f60995..f2c1673b 100644 --- a/lib/createpost/screens/finalpost.dart +++ b/lib/createpost/screens/finalpost.dart @@ -1,5 +1,8 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:post/createpost/model/send_post_model.dart'; import '../../delta_to_html.dart'; @@ -8,6 +11,7 @@ import '../../icons/icon_broken.dart'; import '../controllers/posts_controllers.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import '../services/post_services.dart'; import 'flair_list.dart'; class FinalPost extends StatefulWidget { @@ -17,347 +21,331 @@ class FinalPost extends StatefulWidget { class _FinalPostState extends State { // const FinalPost({Key? key}) : super(key: key); - final PostController controller = Get.put(PostController(), permanent: false); - + final PostController controller = Get.put( + PostController(),permanent: false + ); + final services = PostServices(); @override Widget build(BuildContext context) { return Obx(() => Scaffold( - backgroundColor: Colors.white, - body: Padding( - padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), - child: Column( + backgroundColor: Colors.white, + body: Padding( + padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), + child: Column( + children: [ + // SizedBox(height: 40.0), + Row( children: [ - // SizedBox(height: 40.0), - Row( - children: [ - Padding( - padding: const EdgeInsetsDirectional.only(start: 10.0), - child: IconButton( - color: Colors.black, - onPressed: () { - Get.back(); - }, - icon: Icon(IconBroken.Arrow___Left_2, size: 32.0), - ), - ), - SizedBox( - width: 250.0, - ), - Padding( - padding: EdgeInsetsDirectional.only(end: 1.w), - child: MaterialButton( - onPressed: () { - print(controller.postTitle.value.text); - print((controller.postTitle.value.text as String) - .runtimeType); - print(controller.typeOfPost.value); - print((DeltaToHTML.encodeJson(controller - .textPost.value.document - .toDelta() - .toJson())) - .toString()); - print(controller.urlPost.value.text); - print(controller.idOfSubredditToSubmittPost.value); - print((controller.subredditToSubmitPost.value == - "Myprofile") - ? "User" - : "Subreddit"); - print(controller.isPostNSFW.value); - print(controller.isPostSpoiler.value); - print("send replies ->true"); - print("flair id ${controller.idOfFlair.value}"); - print( - "text of flair ${controller.textOfFlair.value}"); - print("suggested sort hot"); - print("scheduled false"); - print("print data on submit"); - controller.sendPost(context); - controller.postTitle.value.clear(); - controller.urlPost.value.clear(); - controller.textPost.value.clear(); - controller.isPostSpoiler.value = false; - controller.isPostNSFW.value = false; - // Navigator.pop(context); - Get.to(HomeLayoutScreen()); - }, - elevation: 0.0, - height: 40.0, - minWidth: 80.0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0)), - color: Colors.blue[900], - child: Text( - "post", - style: TextStyle( - color: Colors.white, - ), - ), - ), - ) - ], - ), - SizedBox( - height: 25.0, - ), Padding( - padding: const EdgeInsetsDirectional.only(start: 20.0), - child: Row( - children: [ - Row( - children: [ - CircleAvatar( - backgroundImage: NetworkImage( - '${controller.iconOfSubredditToSubmittPost}'), - radius: 16.0, - ), - SizedBox( - width: 4.0, - ), - ElevatedButton.icon( - onPressed: () { - Get.back(); - controller.isPostNSFW.value = false; - controller.isPostSpoiler.value = false; - }, - icon: Text( - controller.subredditToSubmitPost.value, - style: TextStyle(color: Colors.black), - ), - label: Icon( - IconBroken.Arrow___Down_2, - color: Colors.black, - size: 15, - ), - style: ButtonStyle( - elevation: MaterialStateProperty.all(0), - backgroundColor: - MaterialStateProperty.all(Colors.white), - ), - ), - ], - ), - Spacer(), - TextButton( - onPressed: () => showModalBottomSheet( - context: context, - builder: (context) => Center( - child: Column( - mainAxisAlignment: - MainAxisAlignment.center, - children: [ - Expanded( - child: Center( - child: Text( - "Community Standards"))), - ElevatedButton( - style: ButtonStyle( - backgroundColor: - MaterialStateProperty.all( - Colors.blue[900], - ), - ), - onPressed: () { - Navigator.pop(context); - }, - child: Text( - "understand", - style: TextStyle( - color: Colors.white, - ), - ), - ) - ], - ), - )), - child: Text( - "Rules", - style: TextStyle(color: Colors.blue), - )) - ], + padding: const EdgeInsetsDirectional.only(start: 10.0), + child: IconButton( + + color: Colors.black, onPressed: () { + Get.back(); + }, icon:Icon( IconBroken.Arrow___Left_2,size: 32.0), ), ), + SizedBox( + width: 250.0, + ), Padding( - padding: const EdgeInsets.all(16.0), - child: TextFormField( - onChanged: (value) { - controller.postTitle.value; + padding: EdgeInsetsDirectional.only(end: 1.w), + child: MaterialButton( + onPressed: () { + print( controller.postTitle.value.text); + print(( controller.postTitle.value.text as String).runtimeType); + print(controller.typeOfPost.value); + print((DeltaToHTML.encodeJson(controller.textPost.value.document.toDelta().toJson())).toString()); + print(controller.urlPost.value.text); + print(controller.idOfSubredditToSubmittPost.value); + print((controller.subredditToSubmitPost.value == "Myprofile")?"User":"Subreddit"); + print(controller.isPostNSFW.value); + print(controller.isPostSpoiler.value); + print("send replies ->true"); + print("flair id ${controller.idOfFlair.value}"); + print("text of flair ${controller.textOfFlair.value}"); + print("suggested sort hot"); + print("scheduled false"); + print("print data on submit"); + Future str; + if(controller.idOfFlair.value=="") + { + str=controller.sendPost(context, + title: controller.postTitle.value.text, + text: (DeltaToHTML.encodeJson( + controller.textPost.value.document.toDelta() + .toJson())).toString(), + kind: controller.typeOfPost.value, + url: controller.urlPost.value.text, + owner: (controller.idOfSubredditToSubmittPost + .value), + ownerType: controller.subredditToSubmitPost.value=="Myprofile"?"User":"Subreddit", + nsfw: controller.isPostNSFW.value, + spoiler: controller.isPostSpoiler.value, + ); + } + else + { + str= controller.sendPostWithFlair(context, + title: controller.postTitle.value.text, + text: (DeltaToHTML.encodeJson( + controller.textPost.value.document.toDelta() + .toJson())).toString(), + kind: controller.typeOfPost.value, + url: controller.urlPost.value.text, + owner: (controller.idOfSubredditToSubmittPost + .value), + ownerType:controller.subredditToSubmitPost.value=="Myprofile"?"User":"Subreddit", + nsfw: controller.isPostNSFW.value, + spoiler: controller.isPostSpoiler.value, textFlair: controller.textOfFlair.value, idFlair: controller.idOfFlair.value, + ); + } + if(controller.typeOfPost.value=="image") + { + for(int i=0;i(0), - fixedSize: - MaterialStateProperty.all(Size(130.0, 20.0)), - backgroundColor: (controller.isPostNSFW.value) - ? MaterialStateProperty.all( - Colors.black87, - ) - : MaterialStateProperty.all( - Colors.grey[100], - ), - ), - label: Text( - "NSFW", - style: TextStyle( - color: Colors.grey[400], - ), + backgroundColor: + MaterialStateProperty.all(Colors.white), ), - icon: Text( - "18", - style: TextStyle( - color: Colors.grey[400], - ), - )), - SizedBox( - width: 10.0, - ), - ElevatedButton.icon( - onPressed: () { - if (controller.isPostSpoiler.value == false) { - controller.isPostSpoiler.value = true; - controller.isPostSpoiler.refresh(); - } else { - controller.isPostSpoiler.value = false; - controller.isPostSpoiler.refresh(); - } - }, - style: ButtonStyle( - elevation: MaterialStateProperty.all(0), - fixedSize: MaterialStateProperty.all(Size(122.0, 20.0)), - backgroundColor: (controller.isPostSpoiler.value) - ? MaterialStateProperty.all( - Colors.black87, - ) - : MaterialStateProperty.all( - Colors.grey[100], - ), ), - label: Text( - "Spoiler", - style: TextStyle( - color: Colors.grey[400], - ), + ], + ), + Spacer(), + TextButton( + onPressed: () => showModalBottomSheet( + context: context, + builder: (context) => Center( + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Expanded( + child: Center( + child: Text( + "Community Standards"))), + ElevatedButton( + style: ButtonStyle( + backgroundColor: + MaterialStateProperty.all( + Colors.blue[900], + ), + ), + onPressed: () { + Navigator.pop(context); + }, + child: Text( + "understand", + style: TextStyle( + color: Colors.white, + ), + ), + ) + ], + ), + )), + child: Text( + "Rules", + style: TextStyle(color: Colors.blue), + )) + ], + ), + ), + Padding( + padding: const EdgeInsets.all(16.0), + child: TextFormField( + onChanged: (value) { + controller.postTitle.value; + }, + controller: controller.postTitle.value, + readOnly: true, + style: TextStyle(fontSize: 20.0), + maxLines: 2, + decoration: InputDecoration( + contentPadding: const EdgeInsets.all(10.0), + border: OutlineInputBorder( + borderSide: BorderSide(color: Colors.black), + borderRadius: BorderRadius.circular(50.0), + )), + ), + ), + Row( + children: [ + SizedBox( + width: 20.0, + ), + ElevatedButton.icon( + onPressed: () { + if (controller.isPostNSFW.value == false) { + controller.isPostNSFW.value = true; + controller.isPostNSFW.refresh(); + } else { + controller.isPostNSFW.value = false; + controller.isPostNSFW.refresh(); + } + }, + style: ButtonStyle( + elevation: MaterialStateProperty.all(0), + fixedSize: + MaterialStateProperty.all(Size(130.0, 20.0)), + backgroundColor: (controller.isPostNSFW.value) + ? MaterialStateProperty.all( + Colors.black87, + ) + : MaterialStateProperty.all( + Colors.grey[100], ), - icon: Icon( - IconBroken.Danger, + ), + label: Text( + "NSFW", + style: TextStyle( color: Colors.grey[400], ), ), - ], - ), + icon: Text( + "18", + style: TextStyle( + color: Colors.grey[400], + ), + )), SizedBox( - height: 8.0, + width: 10.0, ), - Obx( - () => Visibility( - visible: (controller.flairsOfSubreddit.length > 0) - ? true - : false, - child: ListTile( - onTap: () { - Get.to(FlairList()); - }, - horizontalTitleGap: 0.0, - title: Text( - controller.textOfFlair.isEmpty - ? "Add Flar" - : controller.textOfFlair.value, - style: TextStyle( - color: controller.textColorOfFlair.value == "None" - ? Colors.black87 - : HexColor(controller.textColorOfFlair.value), - backgroundColor: - controller.backgroundColorOfFlair.value == "None" - ? Colors.white - : HexColor( - controller.backgroundColorOfFlair.value), - ), - ), - // Text("Add flair"), - leading: Icon(IconBroken.Edit), - trailing: Icon(IconBroken.Arrow___Right_2), + ElevatedButton.icon( + onPressed: () { + if (controller.isPostSpoiler.value == false) { + controller.isPostSpoiler.value = true; + controller.isPostSpoiler.refresh(); + } else { + controller.isPostSpoiler.value = false; + controller.isPostSpoiler.refresh(); + } + }, + style: ButtonStyle( + elevation: MaterialStateProperty.all(0), + fixedSize: MaterialStateProperty.all(Size(122.0, 20.0)), + backgroundColor: (controller.isPostSpoiler.value) + ? MaterialStateProperty.all( + Colors.black87, + ) + : MaterialStateProperty.all( + Colors.grey[100], ), ), - ), - const Divider( - height: 10.0, - color: Colors.grey, + label: Text( + "Spoiler", + style: TextStyle( + color: Colors.grey[400], + ), + ), + icon: Icon( + IconBroken.Danger, + color: Colors.grey[400], + ), ), ], ), - ), - )); - } - - savePost() async { - print(controller.postTitle.value.text); - print(controller.typeOfPost.value); - print((DeltaToHTML.encodeJson( - controller.textPost.value.document.toDelta().toJson())) - .toString()); - print(controller.urlPost.value.text); - print(controller.idOfSubredditToSubmittPost.value); - print((controller.subredditToSubmitPost.value == "Myprofile") - ? "User" - : "Subreddit"); - print(controller.isPostNSFW.value); - print(controller.isPostSpoiler.value); - print("send replies ->true"); - print("flair id ${controller.idOfFlair.value}"); - print("text of flair ${controller.textOfFlair.value}"); - print("suggested sort hot"); - print("scheduled false"); - - final model = SendPostModel( - title: controller.postTitle.value.text, - kind: controller.typeOfPost.value, - text: (DeltaToHTML.encodeJson( - controller.textPost.value.document.toDelta().toJson())) - .toString(), - url: (controller.typeOfPost.value == "link") - ? controller.urlPost.value.text - : "", - owner: controller.idOfSubredditToSubmittPost.value, - ownerType: (controller.subredditToSubmitPost.value == "Myprofile") - ? "User" - : "Subreddit", - nsfw: controller.isPostNSFW.value, - spoiler: controller.isPostSpoiler.value, - sendReplies: true, - flairId: controller.idOfFlair.value, - flairText: controller.textOfFlair.value, - suggestedSort: "hot", - scheduled: false, - ); - print("AFTER TO JASON ${model.toJson()}"); - Get.to(HomeLayoutScreen()); + SizedBox( + height: 8.0, + ), + Obx(()=> + Visibility( + visible: (controller.flairsOfSubreddit.length>0)?true:false, + child: ListTile( + onTap: () + { + Get.to(FlairList()); + }, + horizontalTitleGap: 0.0, + title:Text(controller.textOfFlair.isEmpty?"Add Flar": + controller.textOfFlair.value, + style: TextStyle( + color: controller.textColorOfFlair.value=="None"? + Colors.black87: + HexColor(controller.textColorOfFlair.value), + backgroundColor: controller.backgroundColorOfFlair.value=="None"? + Colors.white: + HexColor(controller.backgroundColorOfFlair.value), + ), + ), + // Text("Add flair"), + leading: Icon(IconBroken.Edit), + trailing: Icon(IconBroken.Arrow___Right_2), + ), + ), + ), + const Divider( + height: 10.0, + color: Colors.grey, + ), + ], + ), + ), + )); } - @override void dispose() { // TODO: implement dispose diff --git a/lib/createpost/services/post_services.dart b/lib/createpost/services/post_services.dart index bfaa06b3..0f821bfb 100644 --- a/lib/createpost/services/post_services.dart +++ b/lib/createpost/services/post_services.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; @@ -5,10 +7,8 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../networks/const_endpoint_data.dart'; import '../../networks/dio_client.dart'; import '../model/send_post_model.dart'; - -class PostServices { - // were final instead of static var - +class PostServices +{ static var dio = Dio(); //static var client =http.Client(); sendPost(SendPostModel model, BuildContext context) async { @@ -16,29 +16,27 @@ class PostServices { DioClient.init(prefs); try { final response = - await DioClient.post(path: createPost, data: model.toJson()); + await DioClient.post(path: createPost, data: model.toJson()); if (response.statusCode == 200 || response.statusCode == 201) { print("response of sending post ${response.data}"); ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + const SnackBar( content: Text("sent successfuly", style: TextStyle(color: Colors.white)), backgroundColor: Colors.green), ); - - // print(response.statusCode); - // print(json.decode(response.data)['message']); } } catch (e) { print("error in sending the post -> $e"); } } - - Future uploadImage(XFile file, String id) async { + Future uploadImage(File file,Future id) async { String fileName = file.path.split('/').last; FormData formData = FormData.fromMap({ - "fileName": await MultipartFile.fromFile(file.path, filename: fileName), + "file": + await MultipartFile.fromFile(file.path, filename:fileName), }); final response = await dio.post("/posts/$id/images", data: formData); } + } diff --git a/lib/createpost/widgets/type_of_post_web.dart b/lib/createpost/widgets/type_of_post_web.dart new file mode 100644 index 00000000..bb620039 --- /dev/null +++ b/lib/createpost/widgets/type_of_post_web.dart @@ -0,0 +1,265 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; +import 'package:get/get.dart'; +import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart'; +// import 'package:html_editor_enhanced/html_editor.dart'; +import 'package:video_player/video_player.dart'; +import '../../createpost/controllers/posts_controllers.dart'; + +class BuildFormTypeWeb extends StatelessWidget { + BuildFormTypeWeb({ + Key? key, + required this.controller, + }) : super(key: key); + + final PostController controller; + @override + Widget build(BuildContext context) { + + return Obx( + () => Form( + key: controller.formKeyUrl, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 10.0), + child: controller.typeOfPost.value == "link" + ? Padding( + padding: const EdgeInsetsDirectional.only(start: 10.0), + child: Container( + width: 1000, + height: 50, + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.white, + ), + + child: TextFormField( + keyboardType: TextInputType.url, + // inputFormatters: [ + // FilteringTextInputFormatter.allow( + // RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$')) + // ], + onChanged: (value) { + controller.urlPost.refresh(); + }, + validator: (value) { + // String pattern = + // r"((https?:www\.)|(https?:\/\/)|(www\.))[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9]{1,6}(\/[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)?"; + RegExp regExp = RegExp( + "((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)"); + if (value!.isEmpty) { + return "Please enter your website"; + } else if (!(regExp.hasMatch(value))) { + return "Website Url must be started from www"; + } else { + return null; + } + }, + controller: controller.urlPost.value, + enabled: true, + style: const TextStyle(fontSize: 14.0), + showCursor: true, + cursorColor: Colors.blue, + cursorHeight: 20.0, + toolbarOptions: const ToolbarOptions( + copy: true, cut: true, paste: true), + textAlign: TextAlign.start, + decoration: const InputDecoration( + hintText: "URL", border: InputBorder.none + //onfieldsubmitted : (string value ) {}دي بتاخد انونيمس فانكشن عشان لو اما اضغط علي سابمت يعمل اكشن معين + ), + ), + ), + ) + : controller.typeOfPost.value == "image" + ? (controller.imageFileList!.length == 0) + ? SizedBox() + : Container( + width: 1000, + height: 500, + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.white, + ), + + child: ListView.separated( + physics: BouncingScrollPhysics(), + scrollDirection: Axis.horizontal, + separatorBuilder: (BuildContext context, index) => + const SizedBox( + width: 20, + ), + itemBuilder: (BuildContext context, index) => + SizedBox( + height: 250, + width: 120, + child: Stack( + //alignment: AlignmentDirectional.topEnd, + children: [ + SizedBox( + height: 200, + width: 100, + ), + Container( + width: 100, + height: 150, + child: Image.file( + File(controller + .imageFileList![index].path), + fit: BoxFit.cover, + )), + Positioned( + top: -20, + right: -15, + child: IconButton( + onPressed: () { + controller.imageFileList! + .removeAt(index); + }, + icon: Icon( + Icons.close, + color: Colors.black, + size: 30, + )), + ), + ], + ), + ), + itemCount: controller.imageFileList!.length, + ), + ) + : (controller.typeOfPost == "video") + ? (controller.videoController.value != null) + ? Container( + width: 1000, + height: 500, + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.white, + ), + + child: FutureBuilder( + future: controller.initializeVideoPlayerFuture, + builder: (context, snapshot) { + if (snapshot.connectionState == + ConnectionState.done) { + // If the VideoPlayerController has finished initialization, use + // the data it provides to limit the aspect ratio of the video. + return AspectRatio( + aspectRatio: controller.videoController + .value!.value.aspectRatio, + // Use the VideoPlayer widget to display the video. + child: Stack( + alignment: + AlignmentDirectional.topEnd, + children: [ + Stack( + children: [ + VideoPlayer(controller + .videoController.value!), + Center( + child: IconButton( + onPressed: () { + controller.playVideo(); + }, + icon: controller + .videoController + .value! + .value + .isPlaying + ? const Icon( + Icons.pause, + color: Colors.white, + size: 30, + ) + : const Icon( + Icons.play_arrow, + color: Colors.white, + size: 30, + ), + ), + ) + ], + ), + IconButton(onPressed: (){ + controller.videoFile.value=null; + controller.videoController.value=null; + }, icon: Icon(Icons.close)) + ]), + ); + } else { + // If the VideoPlayerController is still initializing, show a + // loading spinner. + return const Center( + child: CircularProgressIndicator()); + } + }, + ), + ) + : SizedBox() + : (controller.typeOfPost == "self") + ? Padding( + padding: const EdgeInsetsDirectional.only( + start: 10.0), + child: Container( + width: 1000, + height: 500, + decoration: BoxDecoration( + border: Border.all(color: Colors.black), + color: Colors.white, + ), + child: Column( + children: [ + quill.QuillToolbar.basic( + multiRowsDisplay: true, + controller: controller.textPost.value, + ), + Expanded( + child: Padding( + padding: const EdgeInsets.all(30.0), + child: quill.QuillEditor( + customStyles: quill.DefaultStyles( + color: Colors.red), + showCursor: true, + paintCursorAboveText: true, + focusNode: FocusNode(), + scrollController: ScrollController(), + scrollable: true, + padding: EdgeInsetsDirectional.only( + start: 10.0), + autoFocus: true, + expands: true, + controller: controller.textPost.value, + readOnly: false, + ), + ), + ) + ], + ), + ) + + // child: TextFormField( + // controller: controller.textPost.value, + // enabled: true, + // style: const TextStyle(fontSize: 16.0), + // showCursor: true, + // cursorColor: Colors.blue, + // cursorHeight: 20.0, + // toolbarOptions: + // const ToolbarOptions(copy: true, cut: true, paste: true), + // keyboardType: TextInputType.multiline, + // textInputAction: TextInputAction.newline, + // autofocus: true, + // maxLines: null, + // textAlign: TextAlign.start, + // decoration: const InputDecoration( + // hintText: "Add optional body text", + // border: InputBorder.none), + // ), + ) + : SizedBox()), + ), + ); + } +} diff --git a/lib/discover/discover.dart b/lib/discover/discover.dart deleted file mode 100644 index 69ea349f..00000000 --- a/lib/discover/discover.dart +++ /dev/null @@ -1,10 +0,0 @@ -import 'package:flutter/cupertino.dart'; - -class discoverScreen extends StatelessWidget { - const discoverScreen({Key? key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(); - } -} diff --git a/lib/discover/models/discover_data.dart b/lib/discover/models/discover_data.dart index f8d47945..aca12742 100644 --- a/lib/discover/models/discover_data.dart +++ b/lib/discover/models/discover_data.dart @@ -4,7 +4,8 @@ class DiscoverData { List>? imgAndVideoList; List? allPosts; DiscoverData({required this.allPosts, required this.imgAndVideoList}); - + // ===================================this function used to===========================================// +//=================to change json to model===========================// DiscoverData.fromJson(Map json) { List> tempDataImagesAndVideo = []; List tempData = []; @@ -23,12 +24,9 @@ class DiscoverData { 'Url': imagesAndVideos['video'] }); } - PostModel temp = PostModel(); temp.fromJson(imagesAndVideos); tempData.add(temp); - - //PostModel(approved: ,author: ,commentCount: ,createdAt: ,flairId: ,images: ,isDeleted: ,isSaved: ,isHidden: ,isModerator: ,isSpam: ,kind: ,locked: ,nsfw: ,maxHeightImageSize: ) }); imgAndVideoList = tempDataImagesAndVideo; allPosts = tempData; diff --git a/lib/discover/providers/discover_provider.dart b/lib/discover/providers/discover_provider.dart index 712dff5f..1f374cd1 100644 --- a/lib/discover/providers/discover_provider.dart +++ b/lib/discover/providers/discover_provider.dart @@ -12,15 +12,17 @@ class DiscoverProvider with ChangeNotifier { DiscoverData? get gettingImagesAndVideo { return imgAndVideoList; } - +// ===================================this function used to===========================================// +//==================fetch and set date===========================// +//topics==> topics of comminty +//page==> page number to fetch +//limit> limit of size data return Future fetchAndSetDiscover(String topic,int page, int limit,BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); - print('====================in discover================================'); - print('/subreddits/${topic}/posts/like_reels$page p $limit L'); await DioClient.get( - path: '/subreddits/study/posts/like_reels', + path: '/subreddits/${topic}/posts/like_reels', query: {'page': page, 'limit': limit}).then((response) { print(response.data); imgAndVideoList = DiscoverData.fromJson(response.data); diff --git a/lib/discover/screens/discover_screen.dart b/lib/discover/screens/discover_screen.dart index b02e2fe8..d90eda0f 100644 --- a/lib/discover/screens/discover_screen.dart +++ b/lib/discover/screens/discover_screen.dart @@ -18,9 +18,8 @@ class DiscoverScreen extends StatefulWidget { class _DiscoverScreenState extends State with TickerProviderStateMixin { + //========================================ButtonsTabBar============================================// TabController? _controller; - - ButtonsTabBar get _tabBar => ButtonsTabBar( controller: _controller, backgroundColor: Colors.grey, @@ -35,6 +34,7 @@ class _DiscoverScreenState extends State radius: 200, tabs: tabs, ); + //===============================================================================================// // drawer functions void showDrawer(BuildContext context) { Scaffold.of(context).openDrawer(); @@ -133,7 +133,6 @@ class _DiscoverScreenState extends State children: topicsName .map((topic) => Tab( child: GridViewDiscover( - // userName: widget.userName, topic:topic, ))) .toList())) diff --git a/lib/discover/widgets/grid_view_discover.dart b/lib/discover/widgets/grid_view_discover.dart index 1e916406..2eafa2a1 100644 --- a/lib/discover/widgets/grid_view_discover.dart +++ b/lib/discover/widgets/grid_view_discover.dart @@ -24,47 +24,7 @@ class GridViewDiscover extends StatefulWidget { } class _GridViewDiscoverState extends State { - DiscoverData? imgAndVideoList - // = DiscoverData( - // imgAndVideoList: ([ - // { - // 'Url': - // 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'https://images.unsplash.com/photo-1447752875215-b2761acb3c5d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'https://images.unsplash.com/photo-1447752875215-b2761acb3c5d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'https://images.unsplash.com/photo-1531804226530-70f8004aa44e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=869&q=80', - // 'subredditName': 'subredditName' - // }, - // { - // 'Url': - // 'https://images.unsplash.com/photo-1465056836041-7f43ac27dcb5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=871&q=80', - // 'subredditName': 'subredditName' - // }, - // ])) - ; - + DiscoverData? imgAndVideoList; int _page = 1; final int _limit = 25; bool _isInit = true; @@ -72,6 +32,8 @@ class _GridViewDiscoverState extends State { bool _isLoadMoreRunning = false; ScrollController _scrollController = new ScrollController(); var userName; + //=====================================this function is used to======================================// + //=================Loading More Data====================// void loadMore() async { if (_isLoading == false && _isLoadMoreRunning == false && @@ -99,8 +61,11 @@ class _GridViewDiscoverState extends State { }); } } - + //=====================================this function is used to======================================// + //=================Start loading More Data====================// bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; + //=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override void didChangeDependencies() async { // TODO: implement didChangeDependencies @@ -142,11 +107,8 @@ class _GridViewDiscoverState extends State { ? MasonryGridView.count( controller: _scrollController, itemCount: imgAndVideoList!.imgAndVideoList!.length, - //No of column crossAxisCount: 2, - // Vertical gap between two items mainAxisSpacing: 0, - // horizontal gap between two items crossAxisSpacing: 0, itemBuilder: (context, index) { return InkWell( diff --git a/lib/discover/widgets/post_video_in_discover.dart b/lib/discover/widgets/post_video_in_discover.dart index 8db5e3e1..7bf49f90 100644 --- a/lib/discover/widgets/post_video_in_discover.dart +++ b/lib/discover/widgets/post_video_in_discover.dart @@ -5,7 +5,6 @@ import 'package:chewie/chewie.dart'; class PostVideoInDiscover extends StatefulWidget { final String url; - // final VideoPlayerController videoController; final double height; final bool inView; const PostVideoInDiscover( @@ -22,6 +21,8 @@ class _PostVideoInDiscoverState extends State { late ChewieController chewieController; bool autoPlay = true; late VideoPlayerController videoPlayerController; + //=====================================this function is used to======================================// + //=================initilize Video====================// @override void initState() { super.initState(); diff --git a/lib/home/controller/home_controller.dart b/lib/home/controller/home_controller.dart index f6d30f0f..05290a4a 100644 --- a/lib/home/controller/home_controller.dart +++ b/lib/home/controller/home_controller.dart @@ -1,3 +1,6 @@ +import 'dart:collection'; +import 'dart:io'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:get/get.dart'; @@ -6,36 +9,38 @@ import 'package:post/myprofile/models/myprofile_data.dart'; import 'package:post/networks/const_endpoint_data.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../comments/models/comment_model.dart'; +import '../../createpost/controllers/posts_controllers.dart'; import '../../networks/dio_client.dart'; import '../../post/models/post_model.dart'; class HomeController extends GetxController with StateMixin> { - RxString sortHistoryBy = "upvoted".obs; - RxString sortHomePostsBy = "best".obs; - RxString sortAllBy = "hot".obs; - - Rx allIcon = Icons.local_fire_department_rounded.obs; - RxInt pageNumber = 1.obs; - List homePosts = [].obs; - List allPosts = [].obs; - List userSavedPosts = [].obs; - List userSavedComments = [].obs; + RxString sortHistoryBy="upvoted".obs; + RxString sortHomePostsBy="best".obs; + RxString sortAllBy="hot".obs; + + RxallIcon=Icons.local_fire_department_rounded.obs; + RxInt pageNumber=1.obs; + ListhomePosts=[].obs; + ListallPosts=[].obs; + ListuserSavedPosts=[].obs; + ListuserSavedComments=[].obs; // ListupvotedPosts=[].obs; // ListdownvotedPosts=[].obs; // ListhiddenPosts=[].obs; - List historyPosts = [].obs; - RxBool isRecentlyVisitedDrawer = false.obs; - List recentlyVisited = [].obs; + ListhistoryPosts=[].obs; + RxBool isRecentlyVisitedDrawer=false.obs; + List recentlyVisited = [ + ].obs; //ListmyCommunities=[].obs; List following = [].obs; RxBool isRecentlyVisitedPannelExpanded = true.obs; RxBool isModeratingPannelExpanded = true.obs; RxBool isFollowingPannelExpanded = true.obs; RxBool isYourCommunitiesPannelExpanded = true.obs; - MyProfileData? myProfile; + MyProfileData? myProfile ; - ///////// for scrol in home////////////////////////// - ScrollController myScroll = ScrollController(); + ///////// for scrol in home////////////////////////// + ScrollController myScroll =ScrollController(); /// true when posts are loading. RxBool isLoading = false.obs; @@ -43,25 +48,22 @@ class HomeController extends GetxController with StateMixin> { /// true when error occurred RxBool error = false.obs; ///////////////////////for in all////////////// - ScrollController myScrollAll = ScrollController(); - RxInt pageNumberAll = 1.obs; - + ScrollController myScrollAll =ScrollController(); +RxInt pageNumberAll=1.obs; /// true when posts are loading. RxBool isLoadingAll = false.obs; /// true when error occurred RxBool errorAll = false.obs; //////History////////////// - RxInt pageNumberHistory = 1.obs; - + RxInt pageNumberHistory=1.obs; /// true when posts are loading. RxBool isLoadingHistory = false.obs; /// true when error occurred RxBool errorHistory = false.obs; //////////////SAVED///////////// - RxInt pageNumberSaved = 1.obs; - + RxInt pageNumberSaved=1.obs; /// true when posts are loading. RxBool isLoadingSaved = false.obs; @@ -69,20 +71,19 @@ class HomeController extends GetxController with StateMixin> { RxBool errorSaved = false.obs; //////////////SAVEDCOMMENTS///////////// - RxInt pageNumberComment = 1.obs; - + RxInt pageNumberComment=1.obs; /// true when posts are loading. RxBool isLoadingCommetns = false.obs; /// true when error occurred RxBool errorComment = false.obs; + @override void onInit() { getInfoOfMe(); super.onInit(); } - Future getInfoOfMe() async { try { final prefs = await SharedPreferences.getInstance(); @@ -92,106 +93,111 @@ class HomeController extends GetxController with StateMixin> { myProfile = MyProfileData.fromJson(response.data['user']); }); } catch (error) { - print( - "there is an error in fetching the data of my profile the error is -> $error"); + print("there is an error in fetching the data of my profile the error is -> $error"); } } - - Future getSavedPosts() async { + Future getSavedPosts({required int p,}) async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - final response = await DioClient.get( - path: '/users/saved?page=${pageNumberSaved}&limit=20', + final response =await DioClient.get( + path:'/users/saved?page=${p}&limit=20', ); - if (response.statusCode == 200) { - for (var post in response.data['savedPosts']) { - PostModel temp = PostModel(); + if(response.statusCode==200) + { + for (var post in response.data['savedPosts']) + { + PostModel temp =PostModel(); await temp.fromJson(post); userSavedPosts.add(temp); } - } else { + } + else { await showToast(response.statusMessage.toString()); - errorSaved.value = true; + errorSaved.value=true; } - isLoadingSaved.value = false; + isLoadingSaved.value=false; } catch (error) { print("error in fetching history posts $error"); change([], status: RxStatus.error(error.toString())); } } - - Future getSavedComments() async { + Future getSavedComments({required int p}) async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - final response = await DioClient.get( - path: '/users/saved?page=${pageNumberComment}&limit=20', + final response =await DioClient.get( + path:'/users/saved?page=${p}&limit=20', ); - if (response.statusCode == 200) { - for (var comment in response.data['savedComments']) { + if(response.statusCode==200) + { + for (var comment in response.data['savedComments']) + { userSavedComments.add(CommentModel.fromJson(comment)); } - } else { + } + else { await showToast(response.statusMessage.toString()); - errorComment.value = true; + errorComment.value=true; } - isLoadingCommetns.value = false; + isLoadingCommetns.value=false; } catch (error) { print("error in fetching saved comments $error"); change([], status: RxStatus.error(error.toString())); } } - - Future getHistory() async { + Future getHistory({required String sort,required int p}) async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - final response = await DioClient.get( - path: '/users/${sortHistoryBy}?page=${pageNumberHistory}&limit=20', + final response =await DioClient.get( + path:'/users/${sort}?page=${p}&limit=20', ); - if (response.statusCode == 200) { - for (var post in response.data['posts']) { - PostModel temp = PostModel(); + if(response.statusCode==200) + { + for (var post in response.data['posts']) + { + PostModel temp =PostModel(); await temp.fromJson(post); historyPosts.add(temp); } - } else { + } + else { await showToast(response.statusMessage.toString()); - errorHistory.value = true; + errorHistory.value=true; } - isLoadingHistory.value = false; + isLoadingHistory.value=false; } catch (error) { print("error in fetching history posts $error"); change([], status: RxStatus.error(error.toString())); } } - - Future getPosts() async { - isLoading.value = true; - error.value = false; + Future getPosts({required String sort,required int p}) async { final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - final response = await DioClient.get( - path: '/users/${sortHomePostsBy}?page=${pageNumberAll}&limit=20', + final response =await DioClient.get( + path:'/users/${sort}?page=${p}&limit=20', ); - if (response.statusCode == 200) { - for (var post in response.data['data']) { - PostModel temp = PostModel(); - await temp.fromJson(post); - homePosts.add(temp); + if(response.statusCode==200) + { + for (var post in response.data['data']) + { + PostModel temp =PostModel(); + await temp.fromJson(post); + homePosts.add(temp); + } + // response.data["data"].forEach((value1) async{ + // PostModel temp =PostModel(); + // await temp.fromJson(value1); + // homePosts.add(temp); + // }); } - // response.data["data"].forEach((value1) async{ - // PostModel temp =PostModel(); - // await temp.fromJson(value1); - // homePosts.add(temp); - // }); - } else { + else { await showToast(response.statusMessage.toString()); - error.value = true; + error.value=true; } - isLoading.value = false; + isLoading.value=false; print("the length of returned list in home is ${homePosts.length}"); print("${homePosts[0]}"); } catch (error) { @@ -199,41 +205,29 @@ class HomeController extends GetxController with StateMixin> { change([], status: RxStatus.error(error.toString())); } } - - Future getPostsInAll() async { + Future getPostsInAll({required String sort,required int p}) async { // isLoading.value=true; // error.value=false; final prefs = await SharedPreferences.getInstance(); DioClient.init(prefs); try { - final response = await DioClient.get( - path: '/users/${sortAllBy}?page=${pageNumber}&limit=20', + final response =await DioClient.get( + path:'/users/${sort}?page=${p}&limit=20', ); - // .then((value) { - // print(value); - // // List data = value.data.map((e) => PostModel.fromJson(value)); - // // change(data, status: RxStatus.success()); - // value.data["data"].forEach((value1){ - // homePosts.add(PostModel.fromJson(value1)); - // }); - // }); - - if (response.statusCode == 200) { - for (var post in response.data['data']) { - PostModel temp = PostModel(); - await temp.fromJson(post); - allPosts.add(temp); - } - // response.data["data"].forEach((value1) async{ - // PostModel temp =PostModel(); - // await temp.fromJson(value1); - // allPosts.add(temp); - // }); - } else { + if(response.statusCode==200) + { + for (var post in response.data['data']) + { + PostModel temp =PostModel(); + await temp.fromJson(post); + allPosts.add(temp); + } + } + else { await showToast(response.statusMessage.toString()); - error.value = true; + error.value=true; } - isLoading.value = false; + isLoading.value=false; print("the length of returned list in all is ${homePosts.length}"); print("${homePosts[0]}"); } catch (error) { @@ -241,7 +235,6 @@ class HomeController extends GetxController with StateMixin> { change([], status: RxStatus.error(error.toString())); } } - Future showToast(final String msg) async { await Fluttertoast.showToast( msg: msg, diff --git a/lib/home/models/flairs.dart b/lib/home/models/flairs.dart index 099dc044..e87a3b1d 100644 --- a/lib/home/models/flairs.dart +++ b/lib/home/models/flairs.dart @@ -1,32 +1,32 @@ -class FlairModel { - String? sId; - String? text; - String? backgroundColor; - String? textColor; - String? permissions; - - FlairModel( - {this.sId, - this.text, - this.backgroundColor, - this.textColor, - this.permissions}); - - FlairModel.fromJson(Map json) { - sId = json['_id']; - text = json['text']; - backgroundColor = json['backgroundColor']; - textColor = json['textColor']; - permissions = json['permissions']; - } - - Map toJson() { - final Map data = new Map(); - data['_id'] = this.sId; - data['text'] = this.text; - data['backgroundColor'] = this.backgroundColor; - data['textColor'] = this.textColor; - data['permissions'] = this.permissions; - return data; - } +class FlairModel { + String? sId; + String? text; + String? backgroundColor; + String? textColor; + String? permissions; + + FlairModel( + {this.sId, + this.text, + this.backgroundColor, + this.textColor, + this.permissions}); + + FlairModel.fromJson(Map json) { + sId = json['_id']; + text = json['text']; + backgroundColor = json['backgroundColor']; + textColor = json['textColor']; + permissions = json['permissions']; + } + + Map toJson() { + final Map data = new Map(); + data['_id'] = this.sId; + data['text'] = this.text; + data['backgroundColor'] = this.backgroundColor; + data['textColor'] = this.textColor; + data['permissions'] = this.permissions; + return data; + } } \ No newline at end of file diff --git a/lib/home/models/test_post_model.dart b/lib/home/models/test_post_model.dart index 55c0f9b0..535885bf 100644 --- a/lib/home/models/test_post_model.dart +++ b/lib/home/models/test_post_model.dart @@ -1,225 +1,225 @@ -class Data { - String? sId; - Author? author; - String? ownerType; - Owner? owner; - List? replies; - FlairId? flairId; - String? flairText; - String? sharedFrom; - String? title; - String? kind; - String? text; - List? images; - String? video; - String? createdAt; - bool? locked; - bool? isDeleted; - bool? sendReplies; - bool? nsfw; - bool? spoiler; - int? votes; - int? views; - int? commentCount; - int? shareCount; - String? suggestedSort; - bool? scheduled; - int? sortOnHot; - int? sortOnBest; - bool? isSpam; - String? url; - bool? isSaved; - int? postVoteStatus; - - Data( - {this.sId, - this.author, - this.ownerType, - this.owner, - this.replies, - this.flairId, - this.flairText, - this.sharedFrom, - this.title, - this.kind, - this.text, - this.images, - this.video, - this.createdAt, - this.locked, - this.isDeleted, - this.sendReplies, - this.nsfw, - this.spoiler, - this.votes, - this.views, - this.commentCount, - this.shareCount, - this.suggestedSort, - this.scheduled, - this.sortOnHot, - this.sortOnBest, - this.isSpam, - this.url, - this.isSaved, - this.postVoteStatus}); - - Data.fromJson(Map json) { - sId = json['_id']; - author = - json['author'] != null ? new Author.fromJson(json['author']) : null; - ownerType = json['ownerType']; - owner = json['owner'] != null ? new Owner.fromJson(json['owner']) : null; - replies = json['replies'].cast(); - flairId = - json['flairId'] != null ? new FlairId.fromJson(json['flairId']) : null; - flairText = json['flairText']; - sharedFrom = json['sharedFrom']; - title = json['title']; - kind = json['kind']; - text = json['text']; - // if (json['images'] != null) { - // images = []; - // json['images'].forEach((v) { - // images!.add(new Null.fromJson(v)); - // }); - // } - video = json['video']; - createdAt = json['createdAt']; - locked = json['locked']; - isDeleted = json['isDeleted']; - sendReplies = json['sendReplies']; - nsfw = json['nsfw']; - spoiler = json['spoiler']; - votes = json['votes']; - views = json['views']; - commentCount = json['commentCount']; - shareCount = json['shareCount']; - suggestedSort = json['suggestedSort']; - scheduled = json['scheduled']; - sortOnHot = json['sortOnHot']; - sortOnBest = json['sortOnBest']; - isSpam = json['isSpam']; - url = json['url']; - isSaved = json['isSaved']; - postVoteStatus = json['postVoteStatus']; - } - - Map toJson() { - final Map data = new Map(); - data['_id'] = this.sId; - if (this.author != null) { - data['author'] = this.author!.toJson(); - } - data['ownerType'] = this.ownerType; - if (this.owner != null) { - data['owner'] = this.owner!.toJson(); - } - data['replies'] = this.replies; - if (this.flairId != null) { - data['flairId'] = this.flairId!.toJson(); - } - data['flairText'] = this.flairText; - data['sharedFrom'] = this.sharedFrom; - data['title'] = this.title; - data['kind'] = this.kind; - data['text'] = this.text; - // if (this.images != null) { - // data['images'] = this.images!.map((v) => v.toJson()).toList(); - // } - data['video'] = this.video; - data['createdAt'] = this.createdAt; - data['locked'] = this.locked; - data['isDeleted'] = this.isDeleted; - data['sendReplies'] = this.sendReplies; - data['nsfw'] = this.nsfw; - data['spoiler'] = this.spoiler; - data['votes'] = this.votes; - data['views'] = this.views; - data['commentCount'] = this.commentCount; - data['shareCount'] = this.shareCount; - data['suggestedSort'] = this.suggestedSort; - data['scheduled'] = this.scheduled; - data['sortOnHot'] = this.sortOnHot; - data['sortOnBest'] = this.sortOnBest; - data['isSpam'] = this.isSpam; - data['url'] = this.url; - data['isSaved'] = this.isSaved; - data['postVoteStatus'] = this.postVoteStatus; - return data; - } -} - -class Author { - String? sId; - String? name; - - Author({this.sId, this.name}); - - Author.fromJson(Map json) { - sId = json['_id']; - name = json['name']; - } - - Map toJson() { - final Map data = new Map(); - data['_id'] = this.sId; - data['name'] = this.name; - return data; - } -} - -class Owner { - String? sId; - String? name; - String? icon; - - Owner({this.sId, this.name, this.icon}); - - Owner.fromJson(Map json) { - sId = json['_id']; - name = json['name']; - icon = json['icon']; - } - - Map toJson() { - final Map data = new Map(); - data['_id'] = this.sId; - data['name'] = this.name; - data['icon'] = this.icon; - return data; - } -} - -class FlairId { - String? sId; - String? text; - String? backgroundColor; - String? textColor; - String? permissions; - - FlairId( - {this.sId, - this.text, - this.backgroundColor, - this.textColor, - this.permissions}); - - FlairId.fromJson(Map json) { - sId = json['_id']; - text = json['text']; - backgroundColor = json['backgroundColor']; - textColor = json['textColor']; - permissions = json['permissions']; - } - - Map toJson() { - final Map data = new Map(); - data['_id'] = this.sId; - data['text'] = this.text; - data['backgroundColor'] = this.backgroundColor; - data['textColor'] = this.textColor; - data['permissions'] = this.permissions; - return data; - } +class Data { + String? sId; + Author? author; + String? ownerType; + Owner? owner; + List? replies; + FlairId? flairId; + String? flairText; + String? sharedFrom; + String? title; + String? kind; + String? text; + List? images; + String? video; + String? createdAt; + bool? locked; + bool? isDeleted; + bool? sendReplies; + bool? nsfw; + bool? spoiler; + int? votes; + int? views; + int? commentCount; + int? shareCount; + String? suggestedSort; + bool? scheduled; + int? sortOnHot; + int? sortOnBest; + bool? isSpam; + String? url; + bool? isSaved; + int? postVoteStatus; + + Data( + {this.sId, + this.author, + this.ownerType, + this.owner, + this.replies, + this.flairId, + this.flairText, + this.sharedFrom, + this.title, + this.kind, + this.text, + this.images, + this.video, + this.createdAt, + this.locked, + this.isDeleted, + this.sendReplies, + this.nsfw, + this.spoiler, + this.votes, + this.views, + this.commentCount, + this.shareCount, + this.suggestedSort, + this.scheduled, + this.sortOnHot, + this.sortOnBest, + this.isSpam, + this.url, + this.isSaved, + this.postVoteStatus}); + + Data.fromJson(Map json) { + sId = json['_id']; + author = + json['author'] != null ? new Author.fromJson(json['author']) : null; + ownerType = json['ownerType']; + owner = json['owner'] != null ? new Owner.fromJson(json['owner']) : null; + replies = json['replies'].cast(); + flairId = + json['flairId'] != null ? new FlairId.fromJson(json['flairId']) : null; + flairText = json['flairText']; + sharedFrom = json['sharedFrom']; + title = json['title']; + kind = json['kind']; + text = json['text']; + // if (json['images'] != null) { + // images = []; + // json['images'].forEach((v) { + // images!.add(new Null.fromJson(v)); + // }); + // } + video = json['video']; + createdAt = json['createdAt']; + locked = json['locked']; + isDeleted = json['isDeleted']; + sendReplies = json['sendReplies']; + nsfw = json['nsfw']; + spoiler = json['spoiler']; + votes = json['votes']; + views = json['views']; + commentCount = json['commentCount']; + shareCount = json['shareCount']; + suggestedSort = json['suggestedSort']; + scheduled = json['scheduled']; + sortOnHot = json['sortOnHot']; + sortOnBest = json['sortOnBest']; + isSpam = json['isSpam']; + url = json['url']; + isSaved = json['isSaved']; + postVoteStatus = json['postVoteStatus']; + } + + Map toJson() { + final Map data = new Map(); + data['_id'] = this.sId; + if (this.author != null) { + data['author'] = this.author!.toJson(); + } + data['ownerType'] = this.ownerType; + if (this.owner != null) { + data['owner'] = this.owner!.toJson(); + } + data['replies'] = this.replies; + if (this.flairId != null) { + data['flairId'] = this.flairId!.toJson(); + } + data['flairText'] = this.flairText; + data['sharedFrom'] = this.sharedFrom; + data['title'] = this.title; + data['kind'] = this.kind; + data['text'] = this.text; + // if (this.images != null) { + // data['images'] = this.images!.map((v) => v.toJson()).toList(); + // } + data['video'] = this.video; + data['createdAt'] = this.createdAt; + data['locked'] = this.locked; + data['isDeleted'] = this.isDeleted; + data['sendReplies'] = this.sendReplies; + data['nsfw'] = this.nsfw; + data['spoiler'] = this.spoiler; + data['votes'] = this.votes; + data['views'] = this.views; + data['commentCount'] = this.commentCount; + data['shareCount'] = this.shareCount; + data['suggestedSort'] = this.suggestedSort; + data['scheduled'] = this.scheduled; + data['sortOnHot'] = this.sortOnHot; + data['sortOnBest'] = this.sortOnBest; + data['isSpam'] = this.isSpam; + data['url'] = this.url; + data['isSaved'] = this.isSaved; + data['postVoteStatus'] = this.postVoteStatus; + return data; + } +} + +class Author { + String? sId; + String? name; + + Author({this.sId, this.name}); + + Author.fromJson(Map json) { + sId = json['_id']; + name = json['name']; + } + + Map toJson() { + final Map data = new Map(); + data['_id'] = this.sId; + data['name'] = this.name; + return data; + } +} + +class Owner { + String? sId; + String? name; + String? icon; + + Owner({this.sId, this.name, this.icon}); + + Owner.fromJson(Map json) { + sId = json['_id']; + name = json['name']; + icon = json['icon']; + } + + Map toJson() { + final Map data = new Map(); + data['_id'] = this.sId; + data['name'] = this.name; + data['icon'] = this.icon; + return data; + } +} + +class FlairId { + String? sId; + String? text; + String? backgroundColor; + String? textColor; + String? permissions; + + FlairId( + {this.sId, + this.text, + this.backgroundColor, + this.textColor, + this.permissions}); + + FlairId.fromJson(Map json) { + sId = json['_id']; + text = json['text']; + backgroundColor = json['backgroundColor']; + textColor = json['textColor']; + permissions = json['permissions']; + } + + Map toJson() { + final Map data = new Map(); + data['_id'] = this.sId; + data['text'] = this.text; + data['backgroundColor'] = this.backgroundColor; + data['textColor'] = this.textColor; + data['permissions'] = this.permissions; + return data; + } } \ No newline at end of file diff --git a/lib/home/screens/all.dart b/lib/home/screens/all.dart index 990a6eb4..273e8d3e 100644 --- a/lib/home/screens/all.dart +++ b/lib/home/screens/all.dart @@ -1,11 +1,19 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:fluttericon/typicons_icons.dart'; import 'package:get/get.dart'; import 'package:post/home/widgets/buttom_nav_bar.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import '../../create_community/screens/create_community.dart'; +import '../../createpost/controllers/posts_controllers.dart'; +import '../../createpost/screens/createpost.dart'; import '../../icons/icon_broken.dart'; +import '../../post/widgets/post.dart'; import '../../post/widgets/post_list.dart'; import '../../widgets/loading_reddit.dart'; import '../controller/home_controller.dart'; +import '../widgets/custom_upper_bar.dart'; +import 'home_layout.dart'; class All extends StatefulWidget { const All({Key? key}) : super(key: key); @@ -14,7 +22,12 @@ class All extends StatefulWidget { } class _AllState extends State with TickerProviderStateMixin { - final HomeController controller = Get.put(HomeController()); + final HomeController controller = Get.put( + HomeController(), + ); + final PostController controllerForPost = Get.put( + PostController(), + ); late AnimationController loadingSpinnerAnimationController; @override void initState() { @@ -23,10 +36,9 @@ class _AllState extends State with TickerProviderStateMixin { AnimationController(duration: const Duration(seconds: 2), vsync: this); loadingSpinnerAnimationController.repeat(); if (controller.allPosts.isEmpty) { - controller.getPostsInAll(); + controller.getPostsInAll(sort: controller.sortAllBy.value,p: controller.pageNumberAll.value); } } - void dispose() { loadingSpinnerAnimationController.dispose(); super.dispose(); @@ -34,13 +46,273 @@ class _AllState extends State with TickerProviderStateMixin { @override Widget build(BuildContext context) { - return Obx( - () => Scaffold( + + double ScreenSizeWidth = MediaQuery.of(context).size.width; + + final isDesktop = ScreenSizeWidth >= 700; + final isMobile = ScreenSizeWidth < 700; + + if (isDesktop) { + return + Obx(()=> + Scaffold( + appBar: PreferredSize( + preferredSize: Size(700, 60), + child: UpBar(controller: controller, controllerForCreatePost: controllerForPost,)), + backgroundColor: const Color(0xA2D4E4FA), + body: + SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + Row( + children: [ + Padding( + padding: EdgeInsetsDirectional.only(start: 200), + child: Column( + children: [ + SizedBox(height: 2,), + Container( + color: Colors.white, + height: 50, + width: 650, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: Image.asset('assets/images/1.png'), + height: 40, + width: 40, + ), + ), + Container( + width: 450.0, + height: 35.0, + color: const Color(0xA2F2F4F6), + child: TextFormField( + onTap: ()=> Get.to(CreatePostSCreen()), + enabled: false, + decoration: const InputDecoration( + border: InputBorder.none, + labelText: 'Create Post', + labelStyle: TextStyle( + color: Colors.grey, + fontSize: 18.0, + ), + ), + ), + ), + SizedBox(width: 10,), + IconButton( + icon:Icon(Icons.photo), + onPressed: () { + Get.to(CreatePostSCreen(), arguments: [ + 0, 0, + 0 + ]); + }, + + ), + const SizedBox( + width: 20, + ), + IconButton( + onPressed: () + { + Get.to(CreatePostSCreen(), arguments: [ + 0, 0, + 0 + ]); + }, + icon:Icon(Icons.insert_link)), + ], + ), + ), + SizedBox(height: 10,), + Container( + color: Colors.white, + height: 50, + width: 650, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="best"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.add_alert_rounded, + size: 15.0, + ), + label: Text('Best'), // <-- Text + ), + height: 80, + width: 80, + ), + ), + + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="hot"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.fireplace, + size: 15.0, + ), + label: Text('Hot'), // <-- Text + ), + SizedBox( + width: 10, + ), + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder(),shadowColor: Colors.blue), + onPressed: () { + controller.sortHomePostsBy.value="new"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.new_releases_outlined, + size: 15.0, + ), + label: Text('New'), // <-- Text + ), + SizedBox( + width: 10, + ), + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="top"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.topic, + size: 15.0, + ), + label: Text('Top'), // <-- Text + ), + SizedBox( + width: 50, + ), + + ], + ), + ), + ], + ), + ), + SizedBox(width:100 ,), + Container( + margin:EdgeInsetsDirectional.only(top: 100) , + height: 300, + width: 350, + color: Colors.white, + child: Column(mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(30), + child: Text("Your personal Reddit frontpage. Come here to check in with your favorite communities."), + ), + SizedBox(height: 50,), + Container( + width: 300, + child: ElevatedButton( + onPressed: () { + Get.to(CreatePostSCreen(),arguments: [0,0,0]); + }, + child: Text(' Create post ',style: TextStyle(color: Colors.white),), + style: ElevatedButton.styleFrom(shape: StadiumBorder(),backgroundColor: Colors.blue), + ), + ), + SizedBox(height: 10,), + Container( + width: 300, + child: OutlinedButton( + onPressed: () { + Get.to(CreateCommunity()); + }, + child: Text('Create Community',style: TextStyle(color: Colors.blue),), + style: OutlinedButton.styleFrom( + shape: StadiumBorder(), + side: BorderSide(width: 2.0, color: Colors.blue), + + ), + ), + ) + ],), + ) + ], + ), + RefreshIndicator( + backgroundColor: Colors.white, + color: Colors.blue[900], + onRefresh: () async { + controller.allPosts.clear(); + controller.pageNumberAll.value = 1; + controller.pageNumberAll.update((val) {}); + controller.getPostsInAll(sort: controller.sortAllBy.value,p: controller.pageNumberAll.value); + controller.update(); + }, + child: controller.isLoading.value + ? Center( + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, + ), + ), + ), + ) + : controller.error.value + ? Text("Unexpected Error Try Again..") + : controller.homePosts.isEmpty + ? LoadingReddit() + //const Text( "No Posts to show") + : PostList( + leftMargin: 200.0, + rightMargin: 650.0, + userName: '${controller.myProfile!.userName}', + updateData: () + { + controller.pageNumberAll.value++; + controller.pageNumberAll.update((val) { }); + }, + data: controller.homePosts, + ), + ), + ], + ), + ), + floatingActionButtonLocation:FloatingActionButtonLocation.miniEndFloat , + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Get.to(HomeLayoutScreen()); + }, + child: Text(' Back to top ',style: TextStyle(color: Colors.white),), + style: ElevatedButton.styleFrom(shape: StadiumBorder(),backgroundColor: Colors.blue), + ), + ), + + + ), + ); + } + return + Obx(()=> Scaffold( bottomNavigationBar: const buttomNavBar( fromProfile: 0, icon: '', - nameOfSubreddit: '', - x: 1, + nameOfSubreddit: '', x: 1, ), backgroundColor: Colors.grey[300], appBar: AppBar( @@ -56,250 +328,218 @@ class _AllState extends State with TickerProviderStateMixin { style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700), ), ), - body: RefreshIndicator( + body: + RefreshIndicator( backgroundColor: Colors.white, color: Colors.blue[900], onRefresh: () async { controller.allPosts.clear(); controller.pageNumberAll.value = 1; - controller.pageNumber.update((val) {}); - controller.getPostsInAll(); + controller.pageNumberAll.update((val) {}); + controller.getPostsInAll(sort: controller.sortAllBy.value, p: controller.pageNumberAll.value); controller.update(); }, child: controller.isLoadingAll.value ? Center( - child: CircularProgressIndicator( - valueColor: loadingSpinnerAnimationController.drive( - ColorTween( - //begin: Colors.blueAccent, - end: Colors.blueAccent, - ), - ), - ), - ) + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, + ), + ), + ), + ) : controller.error.value - ? ListView( - children: const [ - Padding( - padding: EdgeInsets.all(150), - child: Text("Unexpected Error Try Again.."), - ), - ], - ) - : controller.allPosts.isEmpty - ? LoadingReddit() - : PostList( - userName: '${controller.myProfile!.userName}', - updateData: () { - controller.pageNumberAll.value++; - controller.pageNumberAll.update((val) {}); - controller.getPostsInAll(); - }, - data: controller.allPosts, - topOfTheList: Padding( - padding: const EdgeInsetsDirectional.only( - start: 15, top: 5), - child: Row( - children: [ - Icon( - controller.allIcon.value, - color: Colors.grey, - size: 20, - ), - ElevatedButton.icon( - onPressed: () { - showModalBottomSheet( - backgroundColor: Colors.transparent, - context: context, - builder: (context) => GestureDetector( - onTap: () {}, - child: Container( - padding: - const EdgeInsets.all(30), - height: 30.h, - width: 30.w, - margin: const EdgeInsets.all(5), - decoration: BoxDecoration( - borderRadius: - BorderRadius.circular( - 5), - color: Colors.white), - child: Column( - mainAxisAlignment: - MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.start, - mainAxisSize: - MainAxisSize.min, - children: [ - const Text('SORT POSTS BY', - style: TextStyle( - color: Colors.grey, - )), - const Divider( - height: 5, - ), - ListTile( - onTap: () { - controller.sortAllBy - .value = "hot"; - controller - .allIcon.value = - Icons - .local_fire_department_rounded; - controller.sortHistoryBy - .update((val) {}); - Get.back(); - // Get.forceAppUpdate(); - }, - leading: Icon( - Icons - .local_fire_department_rounded, - color: (controller - .sortAllBy - .value == - "hot") - ? Colors.black - : Colors - .grey[500]), - title: Text( - "Hot", - style: TextStyle( - color: (controller - .sortAllBy - .value == - "hot") - ? Colors.black - : Colors - .grey[500]), - ), - trailing: (controller - .sortAllBy - .value == - "hot") - ? Icon( - Icons.done, - color: - Colors.green, - ) - : null, - ), - ListTile( - onTap: () { - controller.sortAllBy - .value = "new"; - controller - .allIcon.value = - Icons - .brightness_low; - controller.sortHistoryBy - .update((val) {}); - Get.back(); - // Get.forceAppUpdate(); - }, - leading: Icon( - Icons.brightness_low, - color: (controller - .sortAllBy - .value == - "new") - ? Colors.black - : Colors - .grey[500]), - title: Text( - "New", - style: TextStyle( - color: (controller - .sortAllBy - .value == - "new") - ? Colors.black - : Colors - .grey[500]), - ), - trailing: (controller - .sortAllBy - .value == - "new") - ? Icon( - Icons.done, - color: - Colors.green, - ) - : null, - ), - ListTile( - onTap: () { - controller.sortAllBy - .value = "top"; - controller - .allIcon.value = - Icons - .turn_sharp_right_sharp; - controller.sortHistoryBy - .update((val) {}); - Get.back(); - // Get.forceAppUpdate(); - }, - leading: Icon( - Icons - .turn_sharp_right_sharp, - color: (controller - .sortAllBy - .value == - "top") - ? Colors.black - : Colors - .grey[500]), - title: Text( - "Top", - style: TextStyle( - color: (controller - .sortAllBy - .value == - "top") - ? Colors.black - : Colors - .grey[500]), - ), - trailing: (controller - .sortAllBy - .value == - "top") - ? Icon( - Icons.done, - color: - Colors.green, - ) - : null, - ), - ], - ), - ), - )); - }, - icon: Text( - "${controller.sortAllBy.value.toUpperCase()}", - style: const TextStyle(color: Colors.grey), + ? ListView( + children: const [ + Padding( + padding: EdgeInsets.all(150), + child: Text("Unexpected Error Try Again.."), + ), + ], + ) + : controller.allPosts.isEmpty + ? LoadingReddit() + : + PostList( + userName: '${controller.myProfile!.userName}', updateData: (){ + controller.pageNumberAll.value++; + controller.pageNumberAll.update((val) { }); + controller.getPostsInAll(sort: controller.sortAllBy.value,p: controller.pageNumberAll.value); + }, data: controller.allPosts, + topOfTheList: + Padding( + padding: const EdgeInsetsDirectional.only(start: 15, top: 5), + child: Row( + children: [ + Icon( + controller.allIcon.value, + color: Colors.grey, + size: 20, + ), + ElevatedButton.icon( + onPressed: () { + showModalBottomSheet( + backgroundColor: Colors.transparent, + context: context, + builder: (context) => GestureDetector( + onTap: () {}, + child: Container( + padding: const EdgeInsets.all(30), + height: 30.h, + width: 30.w, + margin: const EdgeInsets.all(5), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5), + color: Colors.white), + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text('SORT POSTS BY', + style: TextStyle( + color: Colors.grey, + )), + const Divider( + height: 5, ), - label: const Icon( - IconBroken.Arrow___Down_2, - color: Colors.grey, - size: 15, + ListTile( + onTap: () { + controller.sortAllBy.value = "hot"; + controller.allIcon.value = Icons + .local_fire_department_rounded; + controller.sortHistoryBy.update((val) { }); + Get.back(); + // Get.forceAppUpdate(); + + }, + leading: Icon( + Icons + .local_fire_department_rounded, + color: + (controller.sortAllBy.value == + "hot") + ? Colors.black + : Colors.grey[500]), + title: Text( + "Hot", + style: TextStyle( + color: (controller + .sortAllBy.value == + "hot") + ? Colors.black + : Colors.grey[500]), + ), + trailing: + (controller.sortAllBy.value == + "hot") + ? Icon( + Icons.done, + color: Colors.green, + ) + : null, ), - style: ButtonStyle( - elevation: - MaterialStateProperty.all(0), - backgroundColor: MaterialStateProperty.all( - Colors.grey[300]), + ListTile( + onTap: () { + controller.sortAllBy.value = "new"; + controller.allIcon.value = + Icons.brightness_low; + controller.sortHistoryBy.update((val) { }); + Get.back(); + // Get.forceAppUpdate(); + + }, + leading: Icon(Icons.brightness_low, + color: + (controller.sortAllBy.value == + "new") + ? Colors.black + : Colors.grey[500]), + title: Text( + "New", + style: TextStyle( + color: (controller + .sortAllBy.value == + "new") + ? Colors.black + : Colors.grey[500]), + ), + trailing: + (controller.sortAllBy.value == + "new") + ? Icon( + Icons.done, + color: Colors.green, + ) + : null, ), - ), - ], + ListTile( + onTap: () { + controller.sortAllBy.value = "top"; + controller.allIcon.value = + Icons.turn_sharp_right_sharp; + controller.sortHistoryBy.update((val) { }); + Get.back(); + // Get.forceAppUpdate(); + + }, + leading: Icon( + Icons.turn_sharp_right_sharp, + color: + (controller.sortAllBy.value == + "top") + ? Colors.black + : Colors.grey[500]), + title: Text( + "Top", + style: TextStyle( + color: (controller + .sortAllBy.value == + "top") + ? Colors.black + : Colors.grey[500]), + ), + trailing: + (controller.sortAllBy.value == + "top") + ? Icon( + Icons.done, + color: Colors.green, + ) + : null, + ), + ], + ), ), - ), - ), + )); + }, + icon: Text( + "${controller.sortAllBy.value.toUpperCase()}", + style: const TextStyle(color: Colors.grey), + ), + label: const Icon( + IconBroken.Arrow___Down_2, + color: Colors.grey, + size: 15, + ), + style: ButtonStyle( + elevation: MaterialStateProperty.all(0), + backgroundColor: + MaterialStateProperty.all(Colors.grey[300]), + ), + ), + ], + ), + ), + ), ), + + ), - ); + ); } } diff --git a/lib/home/screens/history.dart b/lib/home/screens/history.dart index e031c7d6..400ffb98 100644 --- a/lib/home/screens/history.dart +++ b/lib/home/screens/history.dart @@ -1,11 +1,16 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/material.dart'; import 'package:fluttericon/typicons_icons.dart'; import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; import 'package:post/home/controller/home_controller.dart'; import 'package:post/icons/icon_broken.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import '../../post/widgets/post_list.dart'; import '../../widgets/loading_reddit.dart'; +import '../controller/home_controller.dart'; class History extends StatefulWidget { History({Key? key}) : super(key: key); @@ -26,7 +31,7 @@ class _HistoryState extends Statewith TickerProviderStateMixin { AnimationController(duration: const Duration(seconds: 2), vsync: this); loadingSpinnerAnimationController.repeat(); if (controller.allPosts.isEmpty) { - controller.getHistory(); + controller.getHistory(sort: controller.sortHistoryBy.value, p: controller.pageNumberHistory.value,); } } void dispose() { @@ -61,6 +66,10 @@ class _HistoryState extends Statewith TickerProviderStateMixin { return PopupMenuItem( value: choice, child: ListTile( + onTap: () + { + controller.historyPosts.clear(); + }, leading: Icon(Icons.close_outlined), title: Text(choice), ), @@ -77,7 +86,7 @@ class _HistoryState extends Statewith TickerProviderStateMixin { controller.historyPosts.clear(); controller.pageNumberHistory.value = 1; controller.pageNumberHistory.update((val) {}); - controller.getHistory(); + controller.getHistory(sort: controller.sortHistoryBy.value, p: controller.pageNumberHistory.value,); controller.update(); //Get.forceAppUpdate(); }, @@ -108,7 +117,7 @@ class _HistoryState extends Statewith TickerProviderStateMixin { userName: '${controller.myProfile!.userName}', updateData: (){ controller.pageNumberHistory.value++; controller.pageNumberHistory.update((val) { }); - controller.getHistory(); + controller.getHistory(sort: controller.sortHistoryBy.value, p: controller.pageNumberHistory.value,); }, data: controller.historyPosts, topOfTheList: Padding( diff --git a/lib/home/screens/home_layout.dart b/lib/home/screens/home_layout.dart index 06271396..3d3e6142 100644 --- a/lib/home/screens/home_layout.dart +++ b/lib/home/screens/home_layout.dart @@ -1,16 +1,24 @@ +import 'package:custom_refresh_indicator/custom_refresh_indicator.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; +import 'package:post/create_community/screens/create_community.dart'; import 'package:post/createpost/controllers/posts_controllers.dart'; +import 'package:post/createpost/screens/createpost.dart'; import 'package:post/home/controller/home_controller.dart'; +import 'package:post/home/widgets/community_container.dart'; import 'package:post/home/widgets/new_drawer.dart'; +import 'package:post/post/models/post_model.dart'; import 'package:post/widgets/loading_reddit.dart'; import '../../icons/icon_broken.dart'; +import '../../post/widgets/post.dart'; import '../../post/widgets/post_list.dart'; import '../widgets/buttom_nav_bar.dart'; +import '../widgets/custom_upper_bar.dart'; import '../widgets/end_drawer.dart'; +import '../controller/home_controller.dart'; +import '../../createpost/controllers/posts_controllers.dart'; import '../widgets/recently_visited_list.dart'; -import '../../search/screens/search.dart'; class HomeLayoutScreen extends StatefulWidget { static const routeName = '/homepage'; @@ -69,7 +77,7 @@ class _HomeLayoutScreenState extends State AnimationController(duration: const Duration(seconds: 2), vsync: this); loadingSpinnerAnimationController.repeat(); if (controller.homePosts.isEmpty) { - controller.getPosts(); + controller.getPosts(sort: controller.sortHomePostsBy.value,p: controller.pageNumber.value); } } @@ -78,32 +86,286 @@ class _HomeLayoutScreenState extends State super.dispose(); } - void updateData() { - controller.pageNumber.value++; - controller.getPosts(); - } + // for dropdown list - String dropValue = "Home"; - // Lists for DropDown Menu at appBar List dropdownItems = [ DropdownMenuItem( child: ButtonBar( - children: [Text("Home")], - )), + children: [Text("Home")], + )), DropdownMenuItem( child: ButtonBar( - children: [Text("Popular")], - )) + children: [Text("Popular")], + )) ]; @override Widget build(BuildContext context) { + double ScreenSizeWidth = MediaQuery.of(context).size.width; + + final isDesktop = ScreenSizeWidth >= 700; + final isMobile = ScreenSizeWidth < 700; + + if (isDesktop) { + return + Obx(()=> + Scaffold( + appBar: PreferredSize( + preferredSize: Size(700, 60), + child: UpBar(controller: controller, controllerForCreatePost: controllerForPost,)), + backgroundColor: const Color(0xA2D4E4FA), + body:SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + children: [ + Row( + children: [ + Padding( + padding: EdgeInsetsDirectional.only(start: 200), + child: Column( + children: [ + SizedBox(height: 2,), + Container( + color: Colors.white, + height: 50, + width: 650, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: Image.asset('assets/images/1.png'), + height: 40, + width: 40, + ), + ), + Container( + width: 450.0, + height: 35.0, + color: const Color(0xA2F2F4F6), + child: TextFormField( + onTap: ()=> Get.to(CreatePostSCreen()), + enabled: false, + decoration: const InputDecoration( + border: InputBorder.none, + labelText: 'Create Post', + labelStyle: TextStyle( + color: Colors.grey, + fontSize: 18.0, + ), + ), + ), + ), + SizedBox(width: 10,), + IconButton( + icon:Icon(Icons.photo), + onPressed: () { + Get.to(CreatePostSCreen(), arguments: [ + 0, 0, + 0 + ]); + }, + + ), + const SizedBox( + width: 20, + ), + IconButton( + onPressed: () + { + Get.to(CreatePostSCreen(), arguments: [ + 0, 0, + 0 + ]); + }, + icon:Icon(Icons.insert_link)), + ], + ), + ), + SizedBox(height: 10,), + Container( + color: Colors.white, + height: 50, + width: 650, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.all(8.0), + child: Container( + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="best"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.add_alert_rounded, + size: 15.0, + ), + label: Text('Best'), // <-- Text + ), + height: 80, + width: 80, + ), + ), + + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="hot"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.fireplace, + size: 15.0, + ), + label: Text('Hot'), // <-- Text + ), + SizedBox( + width: 10, + ), + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder(),shadowColor: Colors.blue), + onPressed: () { + controller.sortHomePostsBy.value="new"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.new_releases_outlined, + size: 15.0, + ), + label: Text('New'), // <-- Text + ), + SizedBox( + width: 10, + ), + ElevatedButton.icon( + style: ElevatedButton.styleFrom(shape: StadiumBorder()), + onPressed: () { + controller.sortHomePostsBy.value="top"; + controller.sortHomePostsBy.update((val) { }); + }, + icon: Icon( // <-- Icon + Icons.topic, + size: 15.0, + ), + label: Text('Top'), // <-- Text + ), + SizedBox( + width: 50, + ), + + ], + ), + ), + ], + ), + ), + SizedBox(width:100 ,), + Container( + margin:EdgeInsetsDirectional.only(top: 100) , + height: 300, + width: 350, + color: Colors.white, + child: Column(mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(30), + child: Text("Your personal Reddit frontpage. Come here to check in with your favorite communities."), + ), + SizedBox(height: 50,), + Container( + width: 300, + child: ElevatedButton( + onPressed: () { + Get.to(CreatePostSCreen(),arguments: [0,0,0]); + }, + child: Text(' Create post ',style: TextStyle(color: Colors.white),), + style: ElevatedButton.styleFrom(shape: StadiumBorder(),backgroundColor: Colors.blue), + ), + ), + SizedBox(height: 10,), + Container( + width: 300, + child: OutlinedButton( + onPressed: () { + Get.to(CreateCommunity()); + }, + child: Text('Create Community',style: TextStyle(color: Colors.blue),), + style: OutlinedButton.styleFrom( + shape: StadiumBorder(), + side: BorderSide(width: 2.0, color: Colors.blue), + + ), + ), + ) + ],), + ) + ], + ), + RefreshIndicator( + backgroundColor: Colors.white, + color: Colors.blue[900], + onRefresh: () async { + controller.homePosts.clear(); + controller.pageNumber.value = 1; + controller.pageNumber.update((val) {}); + controller.getPosts(sort: controller.sortHomePostsBy.value,p: controller.pageNumber.value); + controller.update(); + }, + child: controller.isLoading.value + ? Center( + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, + ), + ), + ), + ) + : controller.error.value + ? Text("Unexpected Error Try Again..") + : controller.homePosts.isEmpty + ? LoadingReddit() + //const Text( "No Posts to show") + : PostList( + leftMargin: 200.0, + rightMargin: 650.0, + userName: '${controller.myProfile!.userName}', + updateData: () + { + controller.pageNumber.value++; + controller.pageNumber.update((val) { }); + }, + data: controller.homePosts, + ), + ), + ], + ), + ), + floatingActionButtonLocation:FloatingActionButtonLocation.miniEndFloat , + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Get.to(HomeLayoutScreen()); + }, + child: Text(' Back to top ',style: TextStyle(color: Colors.white),), + style: ElevatedButton.styleFrom(shape: StadiumBorder(),backgroundColor: Colors.blue), + ), + ), + + + ), + ); + } return Obx( - () => Scaffold( + () => Scaffold( appBar: AppBar( - // To make style for status bar - systemOverlayStyle: SystemUiOverlayStyle( + // To make style for status bar + systemOverlayStyle: const SystemUiOverlayStyle( statusBarColor: Colors.white, statusBarIconBrightness: Brightness.dark, ), @@ -131,14 +393,14 @@ class _HomeLayoutScreenState extends State "modsub length ${controllerForPost.moderatedSubreddits.length}"); print("name of ${controllerForPost.moderatedSubreddits[0]}"); }, - icon: Text( + icon: const Text( "Home", style: TextStyle( color: Colors.black, fontSize: 17.0, fontWeight: FontWeight.w600), ), - label: Icon( + label: const Icon( IconBroken.Arrow___Down_2, color: Colors.black, ), @@ -150,9 +412,7 @@ class _HomeLayoutScreenState extends State ), actions: [ IconButton( - onPressed: () { - Navigator.pushNamed(context, Search.routeName); - }, + onPressed: () {}, icon: Icon( IconBroken.Search, color: Colors.black87, @@ -198,13 +458,13 @@ class _HomeLayoutScreenState extends State controller: controller, ), drawer: //RecentlyVisitedDrawer(controller: this.controller,), - (controller.isRecentlyVisitedDrawer.value == true) - ? RecentlyVisitedDrawer( - controller: this.controller, - ) - : MyDrawer( - controller: this.controller, - controllerForCreatePost: this.controllerForPost), + (controller.isRecentlyVisitedDrawer.value == true) + ? RecentlyVisitedDrawer( + controller: this.controller, + ) + : MyDrawer( + controller: this.controller, + controllerForCreatePost: this.controllerForPost), body: RefreshIndicator( backgroundColor: Colors.white, color: Colors.blue[900], @@ -212,50 +472,41 @@ class _HomeLayoutScreenState extends State controller.homePosts.clear(); controller.pageNumber.value = 1; controller.pageNumber.update((val) {}); - controller.getPosts(); + controller.getPosts(sort: controller.sortHomePostsBy.value,p: controller.pageNumber.value); controller.update(); }, child: controller.isLoading.value ? Center( - child: CircularProgressIndicator( - valueColor: loadingSpinnerAnimationController.drive( - ColorTween( - //begin: Colors.blueAccent, - end: Colors.blueAccent, - ), - ), - ), - ) + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, + ), + ), + ), + ) : controller.error.value - ? ListView( - children: const [ - Padding( - padding: EdgeInsets.all(150), - child: Text("Unexpected Error Try Again.."), - ), - ], - ) - : controller.homePosts.isEmpty - ? LoadingReddit() - //const Text( "No Posts to show") - : PostList( - userName: '${controller.myProfile!.userName}', - updateData: updateData, - data: controller.homePosts, - ), - - // : ListView.builder( - // controller: controller.myScroll, - // itemCount: controller.homePosts.length, - // itemBuilder: ( - // final BuildContext ctx, - // final int index, - // ) { - // return Post.home( - // data: controller.homePosts[index], - // ); - // }, - // ), + ? ListView( + children: const [ + Padding( + padding: EdgeInsets.all(150), + child: Text("Unexpected Error Try Again.."), + ), + ], + ) + : controller.homePosts.isEmpty + ? LoadingReddit() + //const Text( "No Posts to show") + : PostList( + userName: '${controller.myProfile!.userName}', + updateData: () + { + controller.pageNumber.value++; + controller.getPosts(sort: controller.sortHomePostsBy.value,p: controller.pageNumber.value); + }, + data: controller.homePosts, + ), ), ), ); diff --git a/lib/home/screens/saved.dart b/lib/home/screens/saved.dart index 79a7b4ae..45ce4179 100644 --- a/lib/home/screens/saved.dart +++ b/lib/home/screens/saved.dart @@ -1,67 +1,71 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:post/home/screens/saved_comments.dart'; import 'package:post/home/screens/saved_posts.dart'; + class Saved extends StatelessWidget { const Saved({Key? key}) : super(key: key); @override Widget build(BuildContext context) { - late TabController controller; - return DefaultTabController( - length: 2, - child: Scaffold( - appBar: PreferredSize( - preferredSize: const Size.fromHeight(100), - child: NestedScrollView( - headerSliverBuilder: - (BuildContext context, bool innerBoxIsScrolled) => [ - SliverAppBar( - backgroundColor: Colors.white, - titleSpacing: 0, - elevation: 2, - titleTextStyle: const TextStyle( - color: Colors.black, - fontWeight: FontWeight.w500, - fontSize: 18), - shadowColor: Colors.white, - title: const Text('Saved'), - bottom: PreferredSize( - preferredSize: const Size.fromHeight(40), - child: TabBar( - indicatorWeight: 3, - indicatorColor: Colors.blue, - indicatorSize: TabBarIndicatorSize.tab, - labelPadding: const EdgeInsets.symmetric(horizontal: 60), - isScrollable: true, - labelStyle: const TextStyle( - fontWeight: FontWeight.w700, fontSize: 14), - labelColor: Colors.black, - unselectedLabelColor: Colors.grey, - tabs: [ - Text( - 'Posts', - style: TextStyle(fontSize: 15), - ), - const Padding( - padding: EdgeInsets.only(bottom: 6), - child: Text( - 'Comments', - ), + late TabController controller; + return + DefaultTabController( + length: 2, + child: Scaffold( + appBar: PreferredSize( + preferredSize: const Size.fromHeight(100), + child: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) =>[ + SliverAppBar( + backgroundColor: Colors.white, + titleSpacing: 0, + elevation: 2, + titleTextStyle: const TextStyle( + color: Colors.black, + fontWeight: FontWeight.w500, + fontSize: 18), + shadowColor: Colors.white, + title: const Text('Saved'), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(40), + child: TabBar( + indicatorWeight: 3, + indicatorColor: Colors.blue, + indicatorSize: TabBarIndicatorSize.tab, + labelPadding: const EdgeInsets.symmetric(horizontal: 60), + isScrollable: true, + labelStyle: const TextStyle( + fontWeight: FontWeight.w700, fontSize: 14), + labelColor: Colors.black, + unselectedLabelColor: Colors.grey, + tabs: [ + Text( + 'Posts', + style: TextStyle(fontSize: 15), + ), + const Padding( + padding: EdgeInsets.only(bottom: 6), + child: Text( + 'Comments', + ), + ), + ], ), - ], - ), + ), ), - ), - ], - body: SizedBox(), + ], + body: SizedBox(), + ), ), + + body: TabBarView( + children: [ + SavedPosts(), + SavedCommentView(), + ]), ), - body: TabBarView(children: [ - SavedPosts(), - SavedCommentView(), - ]), - ), - ); + ); } } diff --git a/lib/home/screens/saved_comments.dart b/lib/home/screens/saved_comments.dart index adcd89bf..25f1981c 100644 --- a/lib/home/screens/saved_comments.dart +++ b/lib/home/screens/saved_comments.dart @@ -1,6 +1,13 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:post/comments/widgets/comment.dart'; +import 'package:responsive_sizer/responsive_sizer.dart'; + + +import '../../networks/const_endpoint_data.dart'; +import '../../post/widgets/post.dart'; +import '../../post/widgets/post_list.dart'; import '../../widgets/loading_reddit.dart'; import '../controller/home_controller.dart'; @@ -11,75 +18,75 @@ class SavedCommentView extends StatefulWidget { State createState() => _SavedCommentViewState(); } -class _SavedCommentViewState extends State - with TickerProviderStateMixin { +class _SavedCommentViewState extends State with TickerProviderStateMixin{ final HomeController controller = Get.put(HomeController()); late AnimationController loadingSpinnerAnimationController; @override - void initState() { + void initState() + { super.initState(); loadingSpinnerAnimationController = AnimationController(duration: const Duration(seconds: 2), vsync: this); loadingSpinnerAnimationController.repeat(); if (controller.userSavedComments.isEmpty) { - controller.getSavedComments(); + controller.getSavedComments(p: controller.pageNumberComment.value, ); } } - void dispose() { loadingSpinnerAnimationController.dispose(); super.dispose(); } - @override Widget build(BuildContext context) { - return Obx( - () => Scaffold( - body: RefreshIndicator( - backgroundColor: Colors.white, - color: Colors.blue[900], - onRefresh: () async { - controller.userSavedComments.clear(); - controller.pageNumberComment.value = 1; - controller.pageNumberComment.update((val) {}); - controller.getSavedComments(); - controller.update(); - //Get.forceAppUpdate(); - }, - child: controller.isLoadingCommetns.value - ? Center( - child: CircularProgressIndicator( - valueColor: loadingSpinnerAnimationController.drive( - ColorTween( - //begin: Colors.blueAccent, - end: Colors.blueAccent, - ), + return Obx(()=> + Scaffold( + body: + RefreshIndicator( + backgroundColor: Colors.white, + color: Colors.blue[900], + onRefresh: () async { + controller.userSavedComments.clear(); + controller.pageNumberComment.value = 1; + controller.pageNumberComment.update((val) {}); + controller.getSavedComments(p: controller.pageNumberComment.value, ); + controller.update(); + //Get.forceAppUpdate(); + }, + child: controller.isLoadingCommetns.value + ? Center( + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, ), ), - ) - : controller.errorComment.value + ), + ) + : controller.errorComment.value ? ListView( - children: const [ - Padding( - padding: EdgeInsets.all(150), - child: Text("Unexpected Error Try Again.."), - ), - ], - ) + children: const [ + Padding( + padding: EdgeInsets.all(150), + child: Text("Unexpected Error Try Again.."), + ), + ], + ) : controller.userSavedComments.isEmpty - ? LoadingReddit() - : ListView.builder( - itemCount: controller.userSavedComments.length, - itemBuilder: ( - final BuildContext ctx, - final int index, - ) { - return Comment( - data: controller.userSavedComments[index], - userName: '${controller.myProfile!.userName}'); - }, - ), - )), + ? LoadingReddit() + + : ListView.builder( + itemCount: controller.userSavedComments.length, + itemBuilder: ( + final BuildContext ctx, + final int index, + ) { + return Comment(data:controller.userSavedComments[index], userName: '${controller.myProfile!.userName}' + ); + }, + ), + ) + ), ); } } diff --git a/lib/home/screens/saved_posts.dart b/lib/home/screens/saved_posts.dart index eca4e9d1..0b7722cf 100644 --- a/lib/home/screens/saved_posts.dart +++ b/lib/home/screens/saved_posts.dart @@ -1,82 +1,87 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; +import 'package:responsive_sizer/responsive_sizer.dart'; + + +import '../../post/widgets/post.dart'; import '../../post/widgets/post_list.dart'; import '../../widgets/loading_reddit.dart'; import '../controller/home_controller.dart'; class SavedPosts extends StatefulWidget { - SavedPosts({Key? key}) : super(key: key); + SavedPosts({Key? key}) : super(key: key); @override State createState() => _SavedPostsState(); } -class _SavedPostsState extends State with TickerProviderStateMixin { +class _SavedPostsState extends State with TickerProviderStateMixin{ final HomeController controller = Get.put(HomeController()); late AnimationController loadingSpinnerAnimationController; @override - void initState() { + void initState() + { super.initState(); loadingSpinnerAnimationController = AnimationController(duration: const Duration(seconds: 2), vsync: this); loadingSpinnerAnimationController.repeat(); if (controller.userSavedPosts.isEmpty) { - controller.getSavedPosts(); + controller.getSavedPosts(p: controller.pageNumberSaved.value, ); } } - void dispose() { loadingSpinnerAnimationController.dispose(); super.dispose(); } - @override Widget build(BuildContext context) { - return Obx( - () => Scaffold( - body: RefreshIndicator( - backgroundColor: Colors.white, - color: Colors.blue[900], - onRefresh: () async { - controller.userSavedPosts.clear(); - controller.pageNumberSaved.value = 1; - controller.pageNumberSaved.update((val) {}); - controller.getSavedPosts(); - controller.update(); - //Get.forceAppUpdate(); - }, - child: controller.isLoadingSaved.value - ? Center( - child: CircularProgressIndicator( - valueColor: loadingSpinnerAnimationController.drive( - ColorTween( - //begin: Colors.blueAccent, - end: Colors.blueAccent, - ), - ), - ), - ) - : controller.errorSaved.value - ? ListView( - children: const [ - Padding( - padding: EdgeInsets.all(150), - child: Text("Unexpected Error Try Again.."), - ), - ], - ) - : controller.userSavedPosts.isEmpty - ? LoadingReddit() - : PostList( - userName: '${controller.myProfile!.userName}', - updateData: () { - controller.pageNumberSaved.value++; - controller.pageNumberSaved.update((val) {}); - controller.getSavedPosts(); - }, - data: controller.userSavedPosts, - ), - ), + return Obx(()=> + Scaffold( + body: + RefreshIndicator( + backgroundColor: Colors.white, + color: Colors.blue[900], + onRefresh: () async { + controller.userSavedPosts.clear(); + controller.pageNumberSaved.value = 1; + controller.pageNumberSaved.update((val) {}); + controller.getSavedPosts(p: controller.pageNumberSaved.value,); + controller.update(); + //Get.forceAppUpdate(); + }, + child: controller.isLoadingSaved.value + ? Center( + child: CircularProgressIndicator( + valueColor: loadingSpinnerAnimationController.drive( + ColorTween( + //begin: Colors.blueAccent, + end: Colors.blueAccent, + ), + ), + ), + ) + : controller.errorSaved.value + ? ListView( + children: const [ + Padding( + padding: EdgeInsets.all(150), + child: Text("Unexpected Error Try Again.."), + ), + ], + ) + : controller.userSavedPosts.isEmpty + ? LoadingReddit() + : + PostList( + userName: '${controller.myProfile!.userName}', updateData: (){ + controller.pageNumberSaved.value++; + controller.pageNumberSaved.update((val) { }); + controller.getSavedPosts(p: controller.pageNumberSaved.value,); + }, data: controller.userSavedPosts, + ), + ) , + ), ); } diff --git a/lib/home/widgets/buttom_nav_bar.dart b/lib/home/widgets/buttom_nav_bar.dart index 8ccf952b..3bf4908d 100644 --- a/lib/home/widgets/buttom_nav_bar.dart +++ b/lib/home/widgets/buttom_nav_bar.dart @@ -8,7 +8,6 @@ import '../../notification/screens/notifications_screen.dart'; import '../../icons/icon_broken.dart'; import '../controller/home_controller.dart'; import '../screens/home_layout.dart'; -import '../../discover/screens/discover_screen.dart'; class buttomNavBar extends StatefulWidget { const buttomNavBar( @@ -50,13 +49,13 @@ class _buttomNavBarState extends State { // duration: Duration(seconds: 2), // curve: Curves.easeOut); // } else { - Get.to(HomeLayoutScreen()); + Get.to(HomeLayoutScreen()); //} } break; case 1: { - Get.to(DiscoverScreen()); + Get.to(HomeLayoutScreen()); } break; case 2: diff --git a/lib/home/widgets/comment_layout.dart b/lib/home/widgets/comment_layout.dart index a2ca2531..38f6a7dc 100644 --- a/lib/home/widgets/comment_layout.dart +++ b/lib/home/widgets/comment_layout.dart @@ -1,10 +1,10 @@ -import 'package:flutter/cupertino.dart'; - -class SavedCommentView extends StatelessWidget { - const SavedCommentView({Key? key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(); - } -} +import 'package:flutter/cupertino.dart'; + +class SavedCommentView extends StatelessWidget { + const SavedCommentView({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Container(); + } +} diff --git a/lib/home/widgets/container_in_recently_visited.dart b/lib/home/widgets/container_in_recently_visited.dart index cb7fe372..fb3b4033 100644 --- a/lib/home/widgets/container_in_recently_visited.dart +++ b/lib/home/widgets/container_in_recently_visited.dart @@ -1,48 +1,48 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:get/get.dart'; -import 'package:get/get_core/src/get_main.dart'; -import 'package:post/home/controller/home_controller.dart'; -import 'package:post/subreddit/screens/subreddit_screen.dart'; - -import '../../create_community/screens/create_community.dart'; -import '../../moderated_subreddit/screens/moderated_subreddit_screen.dart'; -class RecentlyVisitedContainer extends StatelessWidget { - - String nameOfSubreddit=""; - String iconOfSubreddit=''; - RecentlyVisitedContainer( - { - required this.nameOfSubreddit, - required this.iconOfSubreddit, - } - ); - @override - Widget build(BuildContext context) { - return ListTile( - horizontalTitleGap: 0.0, - leading: CircleAvatar(radius: 13,backgroundColor: Colors.blue, - backgroundImage: NetworkImage( - "$iconOfSubreddit" - ), - ), - title: Text("$nameOfSubreddit"), - trailing: IconButton( - onPressed: (){ - - }, - icon: Icon( - Icons.close, - color: Colors.grey, - size: 20 - ), - ), - onTap: () => - Navigator.of(context).pushNamed( - SubredditScreen.routeName, - arguments: nameOfSubreddit) - - - ); - } -} +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; +import 'package:post/home/controller/home_controller.dart'; +import 'package:post/subreddit/screens/subreddit_screen.dart'; + +import '../../create_community/screens/create_community.dart'; +import '../../moderated_subreddit/screens/moderated_subreddit_screen.dart'; +class RecentlyVisitedContainer extends StatelessWidget { + + String nameOfSubreddit=""; + String iconOfSubreddit=''; + RecentlyVisitedContainer( + { + required this.nameOfSubreddit, + required this.iconOfSubreddit, + } + ); + @override + Widget build(BuildContext context) { + return ListTile( + horizontalTitleGap: 0.0, + leading: CircleAvatar(radius: 13,backgroundColor: Colors.blue, + backgroundImage: NetworkImage( + "$iconOfSubreddit" + ), + ), + title: Text("$nameOfSubreddit"), + trailing: IconButton( + onPressed: (){ + + }, + icon: Icon( + Icons.close, + color: Colors.grey, + size: 20 + ), + ), + onTap: () => + Navigator.of(context).pushNamed( + SubredditScreen.routeName, + arguments: nameOfSubreddit) + + + ); + } +} diff --git a/lib/home/widgets/custom_upper_bar.dart b/lib/home/widgets/custom_upper_bar.dart new file mode 100644 index 00000000..86b246cb --- /dev/null +++ b/lib/home/widgets/custom_upper_bar.dart @@ -0,0 +1,443 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:post/create_community/screens/create_community.dart'; +import 'package:post/createpost/screens/createpost.dart'; +import 'package:post/logins/screens/login.dart'; +import 'package:post/notification/screens/notifications_screen.dart'; +import 'package:post/settings/screens/settings.dart'; +import '../../logins/providers/authentication.dart'; +import '../../createpost/controllers/posts_controllers.dart'; +import '../../icons/icon_broken.dart'; +import '../../logins/providers/authentication.dart'; +import '../../myprofile/screens/myprofile_screen.dart'; +import '../../search/screens/search.dart'; +import '../controller/home_controller.dart'; +import '../screens/all.dart'; +import '../screens/home_layout.dart'; +import 'community_container.dart'; + +class UpBar extends StatelessWidget { + final HomeController controller; + final PostController controllerForCreatePost; + UpBar({ + Key? key, + required this.controller, + required this.controllerForCreatePost, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return AppBar( + backgroundColor: Colors.white, + elevation: 0, + leading: GestureDetector( + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 20.0), + child: Image.asset('assets/images/redditlogo.png'), + )), + title: Row( + children: [ + const Text( + 'Reddit', + style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), + ), + const SizedBox( + width: 30, + ), + Container( + width: 220, + child: PopupMenuButton( + child: Row( + children: [ + Icon(Icons.home_filled), + SizedBox( + width: 20, + ), + Text("Home"), + SizedBox( + width: 80, + ), + Icon(Icons.arrow_drop_down_sharp) + ], + ), + elevation: 0, + color: Colors.white, + offset: Offset(0, 43), + itemBuilder: (context) => [ + PopupMenuItem( + value: 1, + child: Container( + width: 220, + child: Text( + "MODERATING", + style: TextStyle(color: Colors.grey, fontSize: 10), + )), + ), + PopupMenuItem( + value: 2, + child: Container( + width: 220, + child: Column( + children: List.generate( + controllerForCreatePost + .moderatedSubreddits.length, + (index) => CommunityContainer( + nameOfSubreddit: controllerForCreatePost + .moderatedSubreddits[index] + .subredditName!, + iconOfSubreddit: (controllerForCreatePost + .moderatedSubreddits[index] + .icon != + null) + ? controllerForCreatePost + .moderatedSubreddits[index].icon! + : '')), + )), + ), + PopupMenuItem( + value: 3, + child: Container( + width: 220, + child: Text( + "YOUR COMMUNITIES", + style: TextStyle(color: Colors.grey, fontSize: 10), + )), + ), + PopupMenuItem( + value: 4, + child: ListTile( + onTap: () { + Get.to(CreateCommunity()); + }, + horizontalTitleGap: 0, + leading: Icon( + Icons.add, + color: Colors.grey, + ), + title: Text( + "Create Community", + style: TextStyle(color: Colors.grey), + ), + ), + ), + PopupMenuItem( + value: 5, + child: Container( + width: 220, + child: Column( + children: List.generate( + controllerForCreatePost + .subscribedSubreddits.length, + (index) => CommunityContainer( + nameOfSubreddit: controllerForCreatePost + .subscribedSubreddits[index] + .subredditName!, + iconOfSubreddit: (controllerForCreatePost + .subscribedSubreddits[index] + .icon != + null) + ? controllerForCreatePost + .subscribedSubreddits[index].icon! + : '')), + )), + ), + PopupMenuItem( + value: 6, + child: Container( + width: 220, + child: Text( + "FEEDS", + style: TextStyle(color: Colors.grey, fontSize: 10), + )), + ), + PopupMenuItem( + value: 7, + child: Column( + children: [ + ListTile( + onTap: () { + Get.to(HomeLayoutScreen()); + }, + horizontalTitleGap: 0, + leading: Icon(Icons.home_filled), + title: Text("Home"), + ), + ListTile( + onTap: () { + Get.to(All()); + }, + horizontalTitleGap: 0, + leading: Icon(Icons.stacked_bar_chart), + title: Text("All"), + ) + ], + )), + ], + )), + Expanded( + child: Container( + width: 350.0, + height: 35.0, + child: TextFormField( + onTap: () { + Get.to(Search()); + }, + enabled: false, + decoration: const InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(20))), + labelText: 'Search Reddit', + prefixIcon: Icon(Icons.search), + labelStyle: TextStyle( + color: Colors.grey, + fontSize: 18.0, + ), + ), + ), + ), + ), + const SizedBox( + width: 20, + ), + IconButton( + onPressed: () { + Get.to(All()); + }, + icon: const Icon( + Icons.arrow_circle_up, + size: 25, + )), + const SizedBox( + width: 20, + ), + IconButton( + onPressed: () { + Get.to(NotificationScreen()); + }, + icon: const Icon( + IconBroken.Notification, + size: 25, + )), + const SizedBox( + width: 20, + ), + IconButton( + onPressed: () { + Get.to(CreatePostSCreen(), arguments: [0, 0, 0]); + }, + icon: const Icon( + Icons.add_sharp, + size: 25, + )), + const SizedBox( + width: 20, + ), + ], + ), + actions: [ + Container( + padding: EdgeInsetsDirectional.only(end: 20, start: 10), + child: PopupMenuButton( + child: Container( + decoration: BoxDecoration( + border: Border.all(color: Colors.black54, width: 0.25)), + width: 270, + height: 20, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 10.0), + child: Row( + children: [ + Stack( + alignment: AlignmentDirectional.bottomEnd, + children: const [ + CircleAvatar( + backgroundImage: + AssetImage("assets/images/reddit.gif"), + radius: 18.0, + ), + CircleAvatar( + backgroundColor: Colors.white, + radius: 6, + ), + Padding( + padding: + EdgeInsetsDirectional.only(end: 2, bottom: 2), + child: CircleAvatar( + backgroundColor: Colors.green, + radius: 4, + ), + ) + ], + ), + const SizedBox( + width: 10, + ), + Padding( + padding: const EdgeInsetsDirectional.only(top: 10.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + Text("Ahmed"), + Text("karma"), + ], + ), + ), + const SizedBox( + width: 100, + ), + const Icon(IconBroken.Arrow___Down_2) + ], + ), + ), + ), + itemBuilder: (context) => [ + PopupMenuItem( + value: 1, + child: Container( + padding: EdgeInsetsDirectional.only(end: 80), + height: 40, + width: 220, + child: ListTile( + horizontalTitleGap: 0, + leading: Icon( + IconBroken.Profile, + color: Colors.grey, + ), + title: Text( + "My Stuff", + style: TextStyle(color: Colors.grey), + ), + ), + ), + ), + PopupMenuItem( + value: 2, + child: Container( + padding: EdgeInsetsDirectional.only(start: 30, bottom: 10), + height: 30, + width: 220, + child: ListTile( + onTap: () { + Navigator.of(context).pushNamed(MyProfileScreen.routeName, + arguments: controller.myProfile!.userName); + // Get.to(MyProfileScreen, + // arguments: controller.myProfile!.userName); + }, + title: Text( + "Profile", + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + PopupMenuItem( + value: 3, + child: Container( + padding: EdgeInsetsDirectional.only(start: 30, bottom: 10), + height: 30, + width: 220, + child: ListTile( + onTap: () { + Get.to(Settings()); + }, + title: Text( + "User settings", + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + PopupMenuItem(child: Divider()), + PopupMenuItem( + value: 4, + child: Container( + padding: EdgeInsetsDirectional.only(end: 0), + height: 40, + width: 220, + child: ListTile( + onTap: () { + Get.to(CreateCommunity()); + }, + horizontalTitleGap: 0, + leading: Padding( + padding: const EdgeInsetsDirectional.only(top: 12.0), + child: Icon( + Icons.r_mobiledata_outlined, + color: Colors.black, + size: 30, + ), + ), + title: Text( + "Create a Community", + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + PopupMenuItem( + value: 5, + child: Container( + padding: EdgeInsetsDirectional.only(start: 40), + height: 40, + width: 220, + child: ListTile( + horizontalTitleGap: 0, + title: Text( + "Privacy Policy", + style: TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + ), + ), + ), + PopupMenuItem(child: Divider()), + PopupMenuItem( + value: 6, + child: Container( + padding: EdgeInsetsDirectional.only(start: 10, bottom: 1), + height: 30, + width: 220, + child: ListTile( + onTap: () { + Auth().logOut(context); + Navigator.of(context).pushNamed(Login.routeName); + }, + horizontalTitleGap: 0, + leading: Icon( + Icons.logout, + size: 25, + color: Colors.black, + ), + title: Text( + "Log out", + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.bold), + ), + ), + ), + ), + PopupMenuItem(child: Divider()), + ], + offset: Offset(0, 59), + color: Colors.white, + elevation: 0, + ), + ), + ], + ); + } +} diff --git a/lib/home/widgets/end_drawer.dart b/lib/home/widgets/end_drawer.dart index b44eea49..b7228032 100644 --- a/lib/home/widgets/end_drawer.dart +++ b/lib/home/widgets/end_drawer.dart @@ -4,7 +4,6 @@ import 'package:get/get.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:post/home/controller/home_controller.dart'; import 'package:post/home/screens/saved.dart'; -import 'package:post/logins/screens/login.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import '../../home/screens/history.dart'; import '../../create_community/screens/create_community.dart'; @@ -12,10 +11,11 @@ import '../../icons/icon_broken.dart'; import '../../myprofile/screens/myprofile_screen.dart'; import '../../settings/screens/settings.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import '../../logins/providers/authentication.dart'; - class endDrawer extends StatelessWidget { - endDrawer({required this.controller, Key? key}) : super(key: key); + + endDrawer({ + required this.controller + ,Key? key}) : super(key: key); final HomeController controller; bool isOnline = true; @@ -84,17 +84,17 @@ class endDrawer extends StatelessWidget { icon: CircleAvatar( radius: 4, backgroundColor: - isOnline ? Colors.green : Colors.grey[200], + isOnline ? Colors.green : Colors.grey[200], ), style: ButtonStyle( elevation: MaterialStateProperty.all(0), backgroundColor: - MaterialStateProperty.all(Colors.grey[200]), + MaterialStateProperty.all(Colors.grey[200]), shape: MaterialStateProperty.all< - RoundedRectangleBorder>( + RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: - BorderRadius.circular(20.0), + BorderRadius.circular(20.0), side: BorderSide( color: isOnline ? Colors.green @@ -103,7 +103,7 @@ class endDrawer extends StatelessWidget { "Online Status: " + "${isOnline ? "On" : "Off"}", style: TextStyle( color: - isOnline ? Colors.green : Colors.black54), + isOnline ? Colors.green : Colors.black54), ), ), ), @@ -122,172 +122,121 @@ class endDrawer extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - GestureDetector( - onTap: () { - showDialog( - context: context, - builder: (ctx) => AlertDialog( - content: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - ), - width: - MediaQuery.of(context).size.width / 1, - height: - MediaQuery.of(context).size.height / 2, - child: (Column( - mainAxisAlignment: - MainAxisAlignment.center, - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - SizedBox( - height: 30, - ), - CircleAvatar( - radius: 70, - backgroundImage: NetworkImage( - "${controller.myProfile!.profilePicture}"), - ), - SizedBox( - height: 130, - ), - Padding( - padding: - const EdgeInsetsDirectional.only( - end: 30), - child: Text( - 'u/${controller.myProfile!.displayName}', - style: TextStyle( - fontSize: 17, - fontWeight: FontWeight.w500), - ), - ), - SizedBox( - height: 10, - ), - Expanded( - child: Row( - children: [ - Expanded( - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - "${controller.myProfile!.postKarma}"), - Text( - "Post Karma", - style: TextStyle( - color: - Colors.grey[400], - fontSize: 14), - ), - ], - ), - ), - SizedBox( - width: 20, - ), - Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - "${controller.myProfile!.commentkarma}"), - Text( - "Comment Karma", - style: TextStyle( - color: Colors.grey[400], - fontSize: 14), - ), - ], - ), - ], - ), - ), - SizedBox( - height: 10, - ), - Padding( - padding: - const EdgeInsetsDirectional.only( - end: 10), - child: ListTile( - onTap: () { - Navigator.of(context).pushNamed( - MyProfileScreen.routeName, - arguments: userName); - }, - leading: Icon( - Icons.account_circle, - color: Colors.black, - ), - title: Text( - "View profile", - style: TextStyle( - color: Colors.black, - fontSize: 16, - fontWeight: FontWeight.w600), - ), - horizontalTitleGap: 0, - ), - ) - ], - )))), - ); - }, - child: Row( - children: [ - Icon( - Icons.ac_unit_outlined, - color: Colors.blue[700], - ), - SizedBox( - width: 5, - ), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "${controller.myProfile!.postKarma}", - style: TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold), - ), - Text( - "karma", - style: TextStyle(color: Colors.grey), - ) - ], - ) - ], - )), - SizedBox( - width: 10, - ), - SizedBox( - width: 10, - ), - GestureDetector( - child: Row( + GestureDetector( + onTap: (){ + showDialog( + context: context, + builder: (ctx) => AlertDialog( + content: Container( + decoration: BoxDecoration( + borderRadius:BorderRadius.circular(20), + ), + width: MediaQuery.of(context).size.width/1, + height: MediaQuery.of(context).size.height/2, + child: ( + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox(height: 30,), + CircleAvatar( + radius:70, + backgroundImage: NetworkImage("${controller.myProfile!.profilePicture}"), + ), + SizedBox(height: 130,), + Padding( + padding: const EdgeInsetsDirectional.only(end: 30), + child: Text( + 'u/${controller.myProfile!.displayName}', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500), + ), + ), + SizedBox(height: 10,), + Expanded( + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("${controller.myProfile!.postKarma}"), + Text("Post Karma", + style: TextStyle( + color: Colors.grey[400], + fontSize: 14 + ), + ), + ], + ), + ), + SizedBox(width:20,), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("${controller.myProfile!.commentkarma}"), + Text("Comment Karma", + style: TextStyle( + color: Colors.grey[400], + fontSize: 14 + ), + ), + ], + ), + ], + ), + ), + SizedBox(height: 10,), + Padding( + padding: const EdgeInsetsDirectional.only(end: 10), + child: ListTile( + onTap: () + { + Navigator.of(context).pushNamed(MyProfileScreen.routeName, + arguments: userName); + }, + leading: Icon(Icons.account_circle,color: Colors.black,), + title: Text("View profile",style: TextStyle(color: Colors.black,fontSize: 16,fontWeight: FontWeight.w600),), + horizontalTitleGap: 0, + ), + ) + ], + ) + ) + ) + ), + ); + }, + child: Row( + children: [ + Icon(Icons.ac_unit_outlined,color: Colors.blue[700],), + SizedBox(width: 5,), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("${controller.myProfile!.postKarma}",style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold),), + Text("karma", + style: TextStyle( + color: Colors.grey + ), + ) + ], + ) + ], + )), + SizedBox(width: 10,), + + SizedBox(width: 10,), + GestureDetector(child: Row( children: [ - Icon( - Icons.text_snippet_rounded, - color: Colors.blue[700], - ), + Icon(Icons.text_snippet_rounded,color: Colors.blue[700],), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - "1m 2d", + Text("1m 2d",style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold),), + Text("Reddit ago", style: TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold), - ), - Text( - "Reddit ago", - style: TextStyle(color: Colors.grey), + color: Colors.grey + ), ) ], ) @@ -321,6 +270,7 @@ class endDrawer extends StatelessWidget { onTap: () { Navigator.of(context).pushNamed(CreateCommunity.routeName); // Navigator.pop(context); + }, ), ListTile( @@ -331,7 +281,7 @@ class endDrawer extends StatelessWidget { style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), ), onTap: () { - Get.to(Saved()); + Get.to(Saved()); }, ), ListTile( @@ -342,24 +292,13 @@ class endDrawer extends StatelessWidget { style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), ), onTap: () { - Get.to(History()); + Get.to(History()); }, ), SizedBox( height: 20.h, ), - ListTile( - horizontalTitleGap: 3, - leading: Icon(IconBroken.Setting), - title: Text( - 'Log out', - style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600), - ), - onTap: () { - Auth().logOut(context); - Navigator.of(context).pushNamed(Login.routeName); - }, - ), + ListTile( horizontalTitleGap: 3, leading: Icon(IconBroken.Setting), @@ -377,4 +316,4 @@ class endDrawer extends StatelessWidget { ), ); } -} +} \ No newline at end of file diff --git a/lib/home/widgets/new_drawer.dart b/lib/home/widgets/new_drawer.dart index f1667eab..3eff29a3 100644 --- a/lib/home/widgets/new_drawer.dart +++ b/lib/home/widgets/new_drawer.dart @@ -245,4 +245,4 @@ class MyDrawer extends StatelessWidget { ), ); } -} +} \ No newline at end of file diff --git a/lib/home/widgets/recently_visited_list.dart b/lib/home/widgets/recently_visited_list.dart index 1d7f0caa..44a3c739 100644 --- a/lib/home/widgets/recently_visited_list.dart +++ b/lib/home/widgets/recently_visited_list.dart @@ -1,74 +1,74 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:get/get.dart'; -import 'package:get/get_core/src/get_main.dart'; -import 'package:post/home/controller/home_controller.dart'; -import 'package:post/home/widgets/community_container.dart'; -import 'package:post/home/widgets/subscribed_community_container.dart'; -import 'package:post/networks/const_endpoint_data.dart'; - -import '../../create_community/screens/create_community.dart'; -import '../../createpost/controllers/posts_controllers.dart'; -import '../../icons/icon_broken.dart'; -import 'container_in_recently_visited.dart'; - -class RecentlyVisitedDrawer extends StatelessWidget { - - final HomeController controller; - const RecentlyVisitedDrawer({ - Key? key, - required this.controller, - }) : super(key: key); - @override - Widget build(BuildContext context) { - return Drawer( - elevation: 20.0, - child: SingleChildScrollView( - child: Column( - children: [ - const SizedBox( - height: 40, - ), - const Divider( - height: 3, - ), - Row( - children: [ - IconButton(onPressed: (){ - controller.isRecentlyVisitedDrawer.value=false; - }, icon: Icon(IconBroken.Arrow___Left_2)), - SizedBox(width: 5,), - Text( - "Recently Visited", - style: TextStyle( - fontWeight: FontWeight.w500, - fontSize: 16, - color: Colors.black), - ), - Spacer(), - TextButton( - onPressed: (){ - controller.recentlyVisited.clear(); - }, child: - Text("Clear all", - style: TextStyle( - color: Colors.grey, - fontSize: 14 - ), - ) - ), - ], - ), - SizedBox(height: 8,), - Column( - children: - List.generate(4, (index) => - RecentlyVisitedContainer(nameOfSubreddit: "coross", iconOfSubreddit: "https://png.pngtree.com/element_our/20190530/ourmid/pngtree-correct-icon-image_1267804.jpg") - ) - ) - ], - ), - ), - ); - } -} +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:get/get_core/src/get_main.dart'; +import 'package:post/home/controller/home_controller.dart'; +import 'package:post/home/widgets/community_container.dart'; +import 'package:post/home/widgets/subscribed_community_container.dart'; +import 'package:post/networks/const_endpoint_data.dart'; + +import '../../create_community/screens/create_community.dart'; +import '../../createpost/controllers/posts_controllers.dart'; +import '../../icons/icon_broken.dart'; +import 'container_in_recently_visited.dart'; + +class RecentlyVisitedDrawer extends StatelessWidget { + + final HomeController controller; + const RecentlyVisitedDrawer({ + Key? key, + required this.controller, + }) : super(key: key); + @override + Widget build(BuildContext context) { + return Drawer( + elevation: 20.0, + child: SingleChildScrollView( + child: Column( + children: [ + const SizedBox( + height: 40, + ), + const Divider( + height: 3, + ), + Row( + children: [ + IconButton(onPressed: (){ + controller.isRecentlyVisitedDrawer.value=false; + }, icon: Icon(IconBroken.Arrow___Left_2)), + SizedBox(width: 5,), + Text( + "Recently Visited", + style: TextStyle( + fontWeight: FontWeight.w500, + fontSize: 16, + color: Colors.black), + ), + Spacer(), + TextButton( + onPressed: (){ + controller.recentlyVisited.clear(); + }, child: + Text("Clear all", + style: TextStyle( + color: Colors.grey, + fontSize: 14 + ), + ) + ), + ], + ), + SizedBox(height: 8,), + Column( + children: + List.generate(4, (index) => + RecentlyVisitedContainer(nameOfSubreddit: "coross", iconOfSubreddit: "https://png.pngtree.com/element_our/20190530/ourmid/pngtree-correct-icon-image_1267804.jpg") + ) + ) + ], + ), + ), + ); + } +} diff --git a/lib/logins/screens/signup.dart b/lib/logins/screens/signup.dart index ddeb5b0b..f24da642 100644 --- a/lib/logins/screens/signup.dart +++ b/lib/logins/screens/signup.dart @@ -18,6 +18,7 @@ import 'package:flutter/foundation.dart' show kIsWeb; import 'login.dart'; import '../widgets/web_image.dart'; +// (kIsWeb) ? Colors.blue : Colors.red class SignUp extends StatefulWidget { const SignUp({Key? key}) : super(key: key); diff --git a/lib/main.dart b/lib/main.dart index b9ce9cc1..c1d391e1 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -79,7 +79,7 @@ import './moderation_settings/screens/traffic_table.dart'; //=====================================Providers====================================================// import './myprofile/providers/myprofile_provider.dart'; import './other_profile/providers/other_profile_provider.dart'; -import './providers/Profile_provider.dart'; +import 'providers/profile_provider.dart'; import 'providers/subreddit_posts_provider.dart'; import './subreddit/providers/subreddit_provider.dart'; import './moderated_subreddit/providers/moderated_subreddit_provider.dart'; @@ -93,6 +93,7 @@ import './settings/provider/user_settings_provider.dart'; import './search/provider/search_provider.dart'; import './discover/providers/discover_provider.dart'; import './moderation_settings/provider/moderation_general_data.dart'; +import './show_post/screens/show_post_web.dart'; import 'widgets/custom_snack_bar.dart'; //import './models/push_notification_model.dart'; import './shared/constants.dart'; @@ -516,9 +517,8 @@ class _MyAppState extends State { // home: CreateCommunity(), //home: homeLayoutScreen(), // home: HomeScreen(), - // home: Login(), - // home: CreateCommunity(), home: Login(), + // home: CreateCommunity(), // home: ForgotUserName(), // home: ForgotPassword(), // home: TraficState(), @@ -620,6 +620,7 @@ class _MyAppState extends State { ModNotificationScreen(), ModeratedSubredditScreen.routeName: (context) => ModeratedSubredditScreen(), + ShowPostDetailsWeb.routeName: (context) => ShowPostDetailsWeb(), // LoginPage.routeName: (context) => LoginPage(), }, ), diff --git a/lib/messages/provider/message_provider.dart b/lib/messages/provider/message_provider.dart index d3cdb0be..4c68236c 100644 --- a/lib/messages/provider/message_provider.dart +++ b/lib/messages/provider/message_provider.dart @@ -1,192 +1,192 @@ -import 'package:dio/dio.dart'; -import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; - -import '../../networks/dio_client.dart'; -import '../../widgets/handle_error.dart'; -import '../models/user_message.dart'; - -class MessageProvider with ChangeNotifier { - Map> messageShow = {}; - List allMessage = []; - List unreadMessage = []; - List sentMessage = []; -//http://localhost:8000/api/v1/subreddits/{subredditName}/moderators/{moderatorName} - Future getAllMessages(context, page, limit) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - messageShow = {}; - await DioClient.get( - path: '/messages', - query: {'page': page, 'limit': limit}).then((value) { - value.data['data'].forEach((element) { - String id; - final message = ShowMessagesModel.fromJson(element); - if (message.type == 'userMessage') { - id = message.subjectId!; - } else { - id = message.sId!; - } - messageShow.putIfAbsent(id, () => []).add(message); - }); - notifyListeners(); - }); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future getUnreadMessages(context, page, limit) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - unreadMessage = []; - await DioClient.get( - path: '/messages/unread', - query: {'page': page, 'limit': limit}).then((value) { - value.data['data'].forEach((element) { - if (element['type'] != 'postReply') { - final message = ShowMessagesModel.fromJson(element); - unreadMessage.add(message); - } - }); - notifyListeners(); - }); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future getSentMessages(context, page, limit) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - sentMessage = []; - await DioClient.get( - path: '/messages/sent', - query: {'page': page, 'limit': limit}).then((value) { - value.data['data'].forEach((element) { - if (element['type'] != 'postReply') { - final message = ShowMessagesModel.fromJson(element); - sentMessage.add(message); - } - }); - notifyListeners(); - }); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future getMessages(context, page, limit) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - allMessage = []; - await DioClient.get( - path: '/messages/all', - query: {'page': page, 'limit': limit}).then((value) { - value.data['data'].forEach((element) { - if (element['type'] != 'postReply') { - final message = ShowMessagesModel.fromJson(element); - allMessage.add(message); - } - }); - notifyListeners(); - }); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future createMessage(data, context) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - DioClient.post(path: '/messages', data: data); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future replyMessage(data, context, messageId) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - - DioClient.post(path: '/messages/$messageId/reply', data: data); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future blockUser(context, userName) async { - //http://localhost:8000/api/v1/users/{userName}/block_user - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - DioClient.post(path: '/users/$userName/block_user', data: {}); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future acceptSubredditInvite(context, subredditName) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - DioClient.post( - path: '/subreddits/$subredditName/accept/invitation', data: {}); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future deleteMessage(context, messageId) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - - DioClient.delete(path: '/messages/$messageId'); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } - - Future markAllAsRead(context) async { - try { - final prefs = await SharedPreferences.getInstance(); - DioClient.init(prefs); - DioClient.patch(path: '/messages/mark_as_read'); - notifyListeners(); - } on DioError catch (e) { - HandleError.errorHandler(e, context); - } catch (error) { - HandleError.handleError(error.toString(), context); - } - } -} +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../networks/dio_client.dart'; +import '../../widgets/handle_error.dart'; +import '../models/user_message.dart'; + +class MessageProvider with ChangeNotifier { + Map> messageShow = {}; + List allMessage = []; + List unreadMessage = []; + List sentMessage = []; +//http://localhost:8000/api/v1/subreddits/{subredditName}/moderators/{moderatorName} + Future getAllMessages(context, page, limit) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + messageShow = {}; + await DioClient.get( + path: '/messages', + query: {'page': page, 'limit': limit}).then((value) { + value.data['data'].forEach((element) { + String id; + final message = ShowMessagesModel.fromJson(element); + if (message.type == 'userMessage') { + id = message.subjectId!; + } else { + id = message.sId!; + } + messageShow.putIfAbsent(id, () => []).add(message); + }); + notifyListeners(); + }); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future getUnreadMessages(context, page, limit) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + unreadMessage = []; + await DioClient.get( + path: '/messages/unread', + query: {'page': page, 'limit': limit}).then((value) { + value.data['data'].forEach((element) { + if (element['type'] != 'postReply') { + final message = ShowMessagesModel.fromJson(element); + unreadMessage.add(message); + } + }); + notifyListeners(); + }); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future getSentMessages(context, page, limit) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + sentMessage = []; + await DioClient.get( + path: '/messages/sent', + query: {'page': page, 'limit': limit}).then((value) { + value.data['data'].forEach((element) { + if (element['type'] != 'postReply') { + final message = ShowMessagesModel.fromJson(element); + sentMessage.add(message); + } + }); + notifyListeners(); + }); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future getMessages(context, page, limit) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + allMessage = []; + await DioClient.get( + path: '/messages/all', + query: {'page': page, 'limit': limit}).then((value) { + value.data['data'].forEach((element) { + if (element['type'] != 'postReply') { + final message = ShowMessagesModel.fromJson(element); + allMessage.add(message); + } + }); + notifyListeners(); + }); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future createMessage(data, context) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + DioClient.post(path: '/messages', data: data); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future replyMessage(data, context, messageId) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + + DioClient.post(path: '/messages/$messageId/reply', data: data); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future blockUser(context, userName) async { + //http://localhost:8000/api/v1/users/{userName}/block_user + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + DioClient.post(path: '/users/$userName/block_user', data: {}); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future acceptSubredditInvite(context, subredditName) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + DioClient.post( + path: '/subreddits/$subredditName/accept/invitation', data: {}); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future deleteMessage(context, messageId) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + + DioClient.delete(path: '/messages/$messageId'); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } + + Future markAllAsRead(context) async { + try { + final prefs = await SharedPreferences.getInstance(); + DioClient.init(prefs); + DioClient.patch(path: '/messages/mark_as_read'); + notifyListeners(); + } on DioError catch (e) { + HandleError.errorHandler(e, context); + } catch (error) { + HandleError.handleError(error.toString(), context); + } + } +} diff --git a/lib/moderated_subreddit/models/moderated_subreddit_data.dart b/lib/moderated_subreddit/models/moderated_subreddit_data.dart deleted file mode 100644 index 481c008b..00000000 --- a/lib/moderated_subreddit/models/moderated_subreddit_data.dart +++ /dev/null @@ -1,60 +0,0 @@ -// //import 'package:flutter_code_style/analysis_options.yaml'; -// import '../../models/subreddit_about _rules.dart'; - -// class ModeratedSubredditData { -// //String? id; -// String? displayName; -// String? name; -// String? subredditPicture; -// String? subredditBackPicture; -// String? description; -// String? subredditLink; -// int? numOfMembers; -// int? numOfOnlines; -// List? rules; -// List? moderators; -// bool? isJoined; -// String? theme; -// ModeratedSubredditData( -// { -// //required this.id, -// required this.name, -// required this.displayName, -// required this.subredditPicture, -// required this.subredditBackPicture, -// required this.description, -// required this.subredditLink, -// required this.numOfMembers, -// required this.numOfOnlines, -// required this.isJoined, -// required this.rules, -// required this.moderators, -// required this.theme}); - -// ModeratedSubredditData.fromJson(Map json) { -// name = json['fixedName']; -// displayName = json['name']; -// subredditPicture = json['icon']; -// subredditBackPicture = json['backgroundImage']; -// description = json['description']; -// subredditLink = (json['subredditLink'] != null) -// ? json['subredditLink'] -// : 'https://www.reddit.com/r/${name.toString()}?utm_medium=android_app&utm_source=share'; -// numOfMembers = int.parse(json['membersCount'].toString()); -// numOfOnlines = 0; //int.parse(json['numOfOnlines'].toString()); -// isJoined = (json['isJoined']); -// final List loadedrule = []; -// json['rules'].forEach((rule) { -// loadedrule.add(SubredditAboutRules(rule['title'], -// (rule['description'] != null) ? rule['description'] : '')); -// }); -// rules = loadedrule; -// final List loadedmodrator = []; -// json['moderators'].forEach((moderator) { -// print( json['moderators']); -// loadedmodrator.add(moderator["userName"]); -// }); -// moderators = loadedmodrator; -// theme = json['theme']; -// } -// } diff --git a/lib/moderated_subreddit/providers/moderated_subreddit_provider.dart b/lib/moderated_subreddit/providers/moderated_subreddit_provider.dart index c94fbe78..388a2d1b 100644 --- a/lib/moderated_subreddit/providers/moderated_subreddit_provider.dart +++ b/lib/moderated_subreddit/providers/moderated_subreddit_provider.dart @@ -13,7 +13,13 @@ class ModeratedSubredditProvider with ChangeNotifier { SubredditData? get gettingSubredditeData { return loadSubreddit; } - + bool showTheme = false; + bool? get gettingTheme { + return showTheme; + } + // ===================================this function used to===========================================// +//==================fetch and set date===========================// +//moderatedSubredditUserName==> userName Of Subreddit Future fetchAndSetModeratedSubredddit( String moderatedSubredditUserName, BuildContext context) async { try { @@ -31,7 +37,10 @@ class ModeratedSubredditProvider with ChangeNotifier { HandleError.handleError(error.toString(), context); } } - + // ===================================this function used to===========================================// +//==================Join and Disjoin subbreddit ===========================// +//moderatedSubredditUserName==> userName Of Subreddit +//action==> action either sub or unsub Future joinAndDisjoinModeratedSubreddit( String moderatedSubredditUserName, String action, @@ -53,4 +62,8 @@ class ModeratedSubredditProvider with ChangeNotifier { return false; } } + Future togglingTheme() async { + showTheme = !showTheme; + notifyListeners(); + } } diff --git a/lib/moderated_subreddit/screens/moderated_subreddit_screen.dart b/lib/moderated_subreddit/screens/moderated_subreddit_screen.dart index 9fc1b2c0..398f49a6 100644 --- a/lib/moderated_subreddit/screens/moderated_subreddit_screen.dart +++ b/lib/moderated_subreddit/screens/moderated_subreddit_screen.dart @@ -3,6 +3,7 @@ import 'package:get/get.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:get/get.dart'; import '../../home/controller/home_controller.dart'; import '../widgets/moderated_subreddit_web.dart'; import '../../models/subreddit_data.dart'; @@ -10,7 +11,9 @@ import '../../widgets/loading_reddit.dart'; import '../widgets/moderated_subreddit_app.dart'; import '../providers/moderated_subreddit_provider.dart'; import '../../home/widgets/end_drawer.dart'; - +import '../../home/controller/home_controller.dart'; +import '../../createpost/controllers/posts_controllers.dart'; +import '../../home/widgets/custom_upper_bar.dart'; class ModeratedSubredditScreen extends StatefulWidget { static const routeName = '/moderatedsubreddit'; @override @@ -58,11 +61,10 @@ SubredditData? loadedSubreddit; _controller!.dispose(); super.dispose(); } - + // ===================================this function used to===========================================// +//==================fetch date for first time===========================// @override void didChangeDependencies() { - // // TODO: implement didChangeDependencies - //===============================Fetch subreddit data =======================================// if (_isInit) { setState(() { _isLoading = true; @@ -81,15 +83,22 @@ SubredditData? loadedSubreddit; }); } _isInit = false; - //==================================================// super.didChangeDependencies(); } - + final HomeController controllerHome = Get.put( + HomeController(), + ); + final PostController controllerForPost = Get.put( + PostController(), + ); @override Widget build(BuildContext context) { final GlobalKey _scaffoldKey = GlobalKey(); return Scaffold( key: _scaffoldKey, + appBar: ( kIsWeb)?PreferredSize( + preferredSize: Size(700, 60), + child: UpBar(controller: controllerHome, controllerForCreatePost: controllerForPost,)):null, body: _isLoading ? LoadingReddit() : kIsWeb diff --git a/lib/moderated_subreddit/widgets/mod_subreddit_post_sort_bottom.dart b/lib/moderated_subreddit/widgets/mod_subreddit_post_sort_bottom.dart index 7dffd43a..1c16e41b 100644 --- a/lib/moderated_subreddit/widgets/mod_subreddit_post_sort_bottom.dart +++ b/lib/moderated_subreddit/widgets/mod_subreddit_post_sort_bottom.dart @@ -43,13 +43,9 @@ class ModSubredditPostSortBottomState @override Widget build(BuildContext context) { return Container( - // height: MediaQuery.of(context).size.height * 0.23, - // width: MediaQuery.of(context).size.width * 1, height: 23.h, width: 10.w, color: const Color.fromARGB(255, 240, 240, 240), - //padding: const EdgeInsets.all(20), - //color: Colors.black54, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.end, @@ -68,7 +64,7 @@ class ModSubredditPostSortBottomState children: [ Icon( _icon, - color: Color.fromARGB(255, 121, 121, 121), + color: const Color.fromARGB(255, 121, 121, 121), size: 25, ), Text( @@ -79,7 +75,7 @@ class ModSubredditPostSortBottomState fontSize: 12), textAlign: TextAlign.end, ), - Icon( + const Icon( color: Color.fromARGB(255, 121, 121, 121), Icons.keyboard_arrow_down_rounded, size: 25, @@ -87,7 +83,7 @@ class ModSubredditPostSortBottomState ]), ), IconButton( - icon: Icon( + icon: const Icon( Icons.shield_outlined, color: Colors.grey, ), @@ -98,7 +94,8 @@ class ModSubredditPostSortBottomState ])); } -//Select the type of Posts + // ===================================this function used to===========================================// +//==================sorting action of Posts===========================// Future typesBottomSheet(BuildContext context) { return showModalBottomSheet( backgroundColor: Colors.transparent, @@ -108,8 +105,6 @@ class ModSubredditPostSortBottomState onTap: () {}, child: Container( padding: const EdgeInsets.all(20), - // height: MediaQuery.of(context).size.height * 0.35, - // width: MediaQuery.of(context).size.width * 0.30, height: 35.h, width: 30.w, margin: const EdgeInsets.all(5), @@ -139,7 +134,7 @@ class ModSubredditPostSortBottomState ), trailing: Visibility( visible: tappedIndex == index, - child: Icon( + child: const Icon( Icons.done, color: Colors.blue, ), @@ -171,7 +166,6 @@ class ModSubredditPostSortBottomState }, ); } - int choosePostType(int index) { tappedIndexTop = null; tappedIndex = index; @@ -221,10 +215,7 @@ class ModSubredditPostSortBottomState : Colors.black, ), onTap: () { - setState(() { - // topValue = - // litemsTop[ - // index1]; + setState(() {; chooseTimeTopPost(index, index1); }); return Navigator.popUntil(context, diff --git a/lib/moderated_subreddit/widgets/moderated_subreddit_app.dart b/lib/moderated_subreddit/widgets/moderated_subreddit_app.dart index c0a0c07e..2e151b8f 100644 --- a/lib/moderated_subreddit/widgets/moderated_subreddit_app.dart +++ b/lib/moderated_subreddit/widgets/moderated_subreddit_app.dart @@ -40,9 +40,6 @@ class ModeratedSubredditApp extends StatelessWidget { foregroundColor: Colors.white, backgroundColor: const Color.fromARGB(137, 33, 33, 33), - // innerBoxIsScrolled - // ? const Color.fromARGB(137, 33, 33, 33) - // : Colors.white, leading: IconButton( onPressed: () { Navigator.of(context).pop(context); @@ -50,7 +47,6 @@ class ModeratedSubredditApp extends StatelessWidget { icon: const Icon(Icons.arrow_back), color: Colors.white, ), - // for saeching in subreddit title: Container( decoration: BoxDecoration( color: const Color.fromARGB(137, 33, 33, 33), @@ -58,7 +54,6 @@ class ModeratedSubredditApp extends StatelessWidget { ), width: 60.w, height: 5.h, - //color: Color.fromARGB(157, 255, 245, 245), child: InkWell( onTap: () { Navigator.of(context) diff --git a/lib/moderated_subreddit/widgets/moderated_subreddit_card_information_web.dart b/lib/moderated_subreddit/widgets/moderated_subreddit_card_information_web.dart index 88d2dba1..444007d4 100644 --- a/lib/moderated_subreddit/widgets/moderated_subreddit_card_information_web.dart +++ b/lib/moderated_subreddit/widgets/moderated_subreddit_card_information_web.dart @@ -2,10 +2,10 @@ import 'package:flutter/material.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:intl/intl.dart'; import '../../models/subreddit_data.dart'; -import '../../moderation_settings/screens/traffic_state.dart'; -import '../../moderation_settings/screens/traffic_table.dart'; - -class ModeratedSubredditCardInformationWeb extends StatelessWidget { +import '../../moderation_settings/screens/moderator_tools_screen.dart'; +import '../providers/moderated_subreddit_provider.dart'; +import 'package:provider/provider.dart'; +class ModeratedSubredditCardInformationWeb extends StatefulWidget { const ModeratedSubredditCardInformationWeb({ Key? key, required this.loadedSubreddit, @@ -13,25 +13,32 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { final SubredditData? loadedSubreddit; + @override + State createState() => + _ModeratedSubredditCardInformationWebState(); +} + +class _ModeratedSubredditCardInformationWebState + extends State { + bool chooseTheme = false; @override Widget build(BuildContext context) { return Expanded( child: Container( - margin: EdgeInsets.only(right: 180, top: 100), - width: 60.w, - height: 32.h, + margin: const EdgeInsets.only(right: 180, top: 100), + width: 50.w, + height: 43.h, color: Colors.white, child: Column( children: [ Container( width: 100.h, height: 6.h, - padding: EdgeInsets.only(top: 10, left: 10), + padding: const EdgeInsets.only(top: 10, left: 10), + color: Colors.blue, child: Row( - //mainAxisAlignment: MainAxisAlignment.start, - //crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( + const Text( 'About Community', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold), @@ -41,15 +48,16 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { ), ElevatedButton( onPressed: () { - Navigator.pushNamed(context, TraficState.routeName, - arguments: loadedSubreddit!.name); + Navigator.of(context).pushNamed( + ModeratorTools.routeName, + arguments: widget.loadedSubreddit!.name); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.transparent), ), child: Row( - children: [ + children: const [ Icon( Icons.shield_outlined, color: Colors.white, @@ -62,12 +70,11 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { )) ], ), - color: Colors.blue, ), Container( width: 100.h, - height: 26.h, - padding: EdgeInsets.only(top: 20, left: 10), + height:32.h, + padding: const EdgeInsets.only(top: 20, left: 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white), @@ -76,27 +83,27 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - '${loadedSubreddit!.description}', - style: TextStyle( + '${widget.loadedSubreddit!.description}', + style: const TextStyle( color: Colors.black, fontWeight: FontWeight.normal), ), Row( children: [ - Icon( + const Icon( Icons.cake_outlined, color: Colors.black, ), Text( - 'Created Apr 30, 2013', - style: TextStyle( + '${DateFormat.yMMMMd('en_US').format(DateTime.parse(widget.loadedSubreddit!.createdAt.toString()))}', + style: const TextStyle( color: Colors.grey, fontWeight: FontWeight.normal), ), ], ), - Divider(), + const Divider(), Container( - padding: EdgeInsets.only(top: 15), + padding: const EdgeInsets.only(top: 15), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, @@ -106,14 +113,13 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.start, children: [ Text( - '${new NumberFormat.compact().format(loadedSubreddit!.numOfMembers) - //loadedSubreddit!.numOfMembers + '${new NumberFormat.compact().format(widget.loadedSubreddit!.numOfMembers) }', - style: TextStyle( + style: const TextStyle( color: Colors.black, fontWeight: FontWeight.bold), ), - Text( + const Text( 'Members', style: TextStyle( color: Colors.grey, @@ -128,8 +134,8 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { children: [ Row( children: [ - Padding( - padding: const EdgeInsetsDirectional.only( + const Padding( + padding: EdgeInsetsDirectional.only( end: 2, bottom: 2), child: CircleAvatar( backgroundColor: Colors.green, @@ -137,16 +143,16 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { ), ), Text( - '${new NumberFormat.compact().format(loadedSubreddit!.numOfOnlines) + '${new NumberFormat.compact().format(widget.loadedSubreddit!.numOfOnlines) //loadedSubreddit!.numOfMembers }', - style: TextStyle( + style: const TextStyle( color: Colors.black, fontWeight: FontWeight.bold), ), ], ), - Text( + const Text( 'Online', style: TextStyle( color: Colors.grey, @@ -157,9 +163,9 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { ], ), ), - Divider(), + const Divider(), Container( - padding: EdgeInsets.only(top: 10, right: 6), + padding: const EdgeInsets.only(top: 10, right: 6), width: 100.w, child: ElevatedButton( style: ButtonStyle( @@ -172,7 +178,7 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { borderRadius: BorderRadius.all(Radius.circular(22)))), ), - child: Text( + child: const Text( 'Create Post', style: TextStyle( fontSize: 13, @@ -181,7 +187,26 @@ class ModeratedSubredditCardInformationWeb extends StatelessWidget { onPressed: () {}, ), ), - Divider(), + const Divider(), + ListTile( + leading: (chooseTheme) + ? Icon(Icons.visibility_outlined) + : Icon(Icons.visibility_off_outlined), + title: Text('Community theme'), + trailing: Switch( + activeColor: Colors.white, + activeTrackColor: Colors.blue, + inactiveThumbColor: Colors.white, + inactiveTrackColor: Colors.grey.shade400, + splashRadius: 50.0, + value: chooseTheme, + onChanged: (value) { + setState(() => chooseTheme = value); + Provider.of(context, listen: true) + .togglingTheme(); + }, + ), + ) ], ), ) diff --git a/lib/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button.dart b/lib/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button.dart index f734b9a6..86bd42b8 100644 --- a/lib/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button.dart +++ b/lib/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button.dart @@ -96,7 +96,8 @@ class ModeratedSubredditPopupMenuButtonState ); } -// To copy Link of Moderated Subreddit + // ===================================this function used to===========================================// +//==================copy Link of Subreddit===========================// Future shareCommunitySheetButton(BuildContext context) { return showModalBottomSheet( backgroundColor: Colors.transparent, @@ -110,8 +111,10 @@ class ModeratedSubredditPopupMenuButtonState ); } -// to disjoin of subreddit + // ===================================the next three function used to===========================================// +//==================to disjoin of subreddit===========================// // have two option one:leave subreddit two: cancel +//communityName==> commuintyUserName you want to leave void _showLeaveDialog(String communityName) { showDialog( context: context, @@ -164,7 +167,9 @@ class ModeratedSubredditPopupMenuButtonState await Provider.of(context, listen: false) .joinAndDisjoinModeratedSubreddit(communityName, 'unsub', context); if (unSub) { - changeDisJoinStatus(); + setState(() { + changeDisJoinStatus(); + }); ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar( isError: false, text: 'Leave Successfully', disableStatus: true), @@ -176,16 +181,14 @@ class ModeratedSubredditPopupMenuButtonState Navigator.of(ctx).pop(); } -// to disjoin change the isJoined status bool changeDisJoinStatus() { - setState(() { - isJoinedstate = false; - }); - + isJoinedstate = false; return isJoinedstate; } -// to join subreddit + // ===================================the next two function used to===========================================// +//==================to join subreddit===========================// +//communityName==> commuintyUserName you want to join void _join(String communityName) async { bool sub = await Provider.of(context, listen: false) @@ -205,12 +208,8 @@ class ModeratedSubredditPopupMenuButtonState } } -// to join change the isJoined status bool changeJoinStatus() { - setState(() { - isJoinedstate = true; - }); - + isJoinedstate = true; return isJoinedstate; } diff --git a/lib/moderated_subreddit/widgets/moderated_subreddit_web.dart b/lib/moderated_subreddit/widgets/moderated_subreddit_web.dart index 1d6b5996..3f27da71 100644 --- a/lib/moderated_subreddit/widgets/moderated_subreddit_web.dart +++ b/lib/moderated_subreddit/widgets/moderated_subreddit_web.dart @@ -1,11 +1,14 @@ import 'package:flutter/material.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import 'package:post/widgets/loading_reddit.dart'; import '../../models/subreddit_about _rules.dart'; import '../../widgets/subreddit_about.dart'; import '../../widgets/subreddit_join_button_web.dart'; import '../../models/subreddit_data.dart'; import '../widgets/moderated_subreddite_post_web.dart'; import '../../widgets/back_to_button.dart'; +import '../screens/moderated_subreddit_screen.dart'; + class ModeratedSubredditWeb extends StatelessWidget { String userName; ModeratedSubredditWeb( @@ -14,23 +17,34 @@ class ModeratedSubredditWeb extends StatelessWidget { required this.tabBar, required this.loadedSubreddit, required this.isLoading, - required this.controller}) { - print(loadedSubreddit!.name); - } - //===============Drawer Bar=====================// + required this.controller}); bool isOnline = true; SubredditData? loadedSubreddit; final TabBar tabBar; bool isLoading; TabController? controller; ScrollController scrollController = ScrollController(); - @override Widget build(BuildContext context) { final GlobalKey _scaffoldKey = GlobalKey(); return Scaffold( key: _scaffoldKey, - floatingActionButton:BackToTopButton(scrollController:scrollController ) , + floatingActionButtonLocation: FloatingActionButtonLocation.miniEndFloat, + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pushNamed(ModeratedSubredditScreen.routeName, + arguments:userName); + }, + child: Text( + ' Back to top ', + style: TextStyle(color: Colors.white), + ), + style: ElevatedButton.styleFrom( + shape: StadiumBorder(), backgroundColor: Colors.blue), + ), + ), body: isLoading ? const Center( child: Icon( @@ -83,7 +97,6 @@ class ModeratedSubredditWeb extends StatelessWidget { left: 0, bottom: 0, child: Container( - // padding: EdgeInsets.only(left: 250), color: Colors.white, child: Column( mainAxisAlignment: @@ -92,10 +105,10 @@ class ModeratedSubredditWeb extends StatelessWidget { CrossAxisAlignment.start, children: [ Container( - //margin: EdgeInsets.only(top: 15), width: 100.w, height: 15.h, - padding: EdgeInsets.only(left: 250), + padding: const EdgeInsets.only( + left: 250), child: Row( crossAxisAlignment: CrossAxisAlignment.center, @@ -105,8 +118,6 @@ class ModeratedSubredditWeb extends StatelessWidget { Container( width: 10.w, height: 20.h, - // margin: EdgeInsets.only(bottom: 30,top: 40), - decoration: BoxDecoration( color: Colors.orange, shape: BoxShape.circle, @@ -120,17 +131,19 @@ class ModeratedSubredditWeb extends StatelessWidget { ), Container( height: 20.h, - margin: - EdgeInsets.only(top: 20), + margin: const EdgeInsets.only( + top: 20), child: Column( children: [ Text( '${loadedSubreddit!.name.toString()}', - style: TextStyle( - fontWeight: - FontWeight - .bold, - fontSize: 35)), + style: + const TextStyle( + fontWeight: + FontWeight + .bold, + fontSize: + 35)), Text( 'r/${loadedSubreddit!.name.toString()}', ), @@ -140,8 +153,6 @@ class ModeratedSubredditWeb extends StatelessWidget { SubredditJoinButtonWeb( isJoined: loadedSubreddit! .isJoined as bool, - // icon: icon, - //dropDownValue: dropDownValue, communityName: loadedSubreddit!.name .toString()), @@ -160,17 +171,11 @@ class ModeratedSubredditWeb extends StatelessWidget { ]; }, body: isLoading - ? const Center( - child: Icon( - Icons.reddit, - color: Colors.blue, - ), - ) + ? LoadingReddit() : TabBarView(controller: controller, children: [ ModeratedSubredditePostWeb( loadedSubreddit: loadedSubreddit, ), - // SubredditPosts(routeNamePop: SubredditScreen.routeName), SubredditAbout( rules: loadedSubreddit!.rules as List, diff --git a/lib/moderated_subreddit/widgets/moderated_subreddite_post_web.dart b/lib/moderated_subreddit/widgets/moderated_subreddite_post_web.dart index 92e0da93..cbfac880 100644 --- a/lib/moderated_subreddit/widgets/moderated_subreddite_post_web.dart +++ b/lib/moderated_subreddit/widgets/moderated_subreddite_post_web.dart @@ -1,81 +1,126 @@ import 'package:flutter/material.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../../widgets/sort_bottom_web.dart'; import '../../models/subreddit_data.dart'; import '../widgets/moderated_subreddit_card_information_web.dart'; +import '../../post/models/post_model.dart'; +import '../../providers/subreddit_posts_provider.dart'; +import '../../widgets/loading_reddit.dart'; +import '../../post/widgets/post_list.dart'; + class ModeratedSubredditePostWeb extends StatefulWidget { final SubredditData? loadedSubreddit; const ModeratedSubredditePostWeb({ Key? key, required this.loadedSubreddit, }) : super(key: key); - - // Posts(this.routeNamePop); @override - State< ModeratedSubredditePostWeb> createState() => _ModeratedSubredditePostWebState(); + State createState() => + _ModeratedSubredditePostWebState(); } -class _ModeratedSubredditePostWebState extends State { +class _ModeratedSubredditePostWebState + extends State { + int _page = 1; + List? posts = []; + bool _isLoadMoreRunning = false; + String? userName; + bool _isInit = true; + bool _isLoading = false; + late ScrollController _scrollController; + //=====================================this function is used to======================================// + //=================Loading More Data====================// + void _loadMore() { + if (_isLoading == false && _isLoadMoreRunning == false) { + setState(() { + toggleLoadingMore(); // Display a progress indicator at the bottom + }); + setState(() { + _page += 1; // Increase _page by one + }); + setState(() { + toggleLoadingMore(); + }); + } + } + //=====================================this function is used to======================================// + //=================Start loading More Data====================// + bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; + //=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override - Widget build(BuildContext context) { - return ListView( - scrollDirection: Axis.vertical, - children: [ - Row( - mainAxisSize: MainAxisSize.min, + Future didChangeDependencies() async { + // TODO: implement didChangeDependencies + if (_isInit) { + setState(() { + _isLoading = true; + }); + //New Hot Top + await Provider.of(context, listen: false) + .fetchSubredditePosts(widget.loadedSubreddit!.name.toString(), 'hot', + _page, 25, context) + .then((value) async { + posts = + await Provider.of(context, listen: false) + .gettingSubredditPostData; + }); + final prefs = await SharedPreferences.getInstance(); + userName = prefs.getString('userName'); + setState(() { + _isLoading = false; + }); + } + _isInit = false; + super.didChangeDependencies(); + } - mainAxisAlignment: MainAxisAlignment.spaceBetween, - //crossAxisAlignment: CrossAxisAlignment., - children: [ - Expanded( - flex: 2, - child: Column( - children: [ - SizedBox( - height: 10.h, - ), - Container( - height: 6.h, - width: 50.w, - margin: EdgeInsets.only(left: 100, top: 40), - child: SortBottomWeb(page: 1,userName: widget.loadedSubreddit!.name.toString(),), - color: Colors.white, - // width: 100.w, - ), - Container( - // padding: const EdgeInsets.only(bottom: 100,), - margin: EdgeInsets.only(left: 100, bottom: 90, top: 30), - height: 30.h, - width: 50.w, - // color: Colors.white, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: const [ - Expanded( - child: ListTile( - title: Text('Post'), - ), - ), - ], - ), - ) - ]), + @override + Widget build(BuildContext context) { + return (_isLoading || _isLoadMoreRunning) + ? LoadingReddit() + : (posts != null) + ? PostList( + leftMargin: 15.w, + rightMargin: 35.w, + topOfTheList: Container( + height: 65.h, + width: 50.h, + margin: EdgeInsets.only(left: 15.w), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ModeratedSubredditCardInformationWeb( + loadedSubreddit: widget.loadedSubreddit), + SortBottomWeb( + page: 1, + userName: widget.loadedSubreddit!.name.toString()), + ], ), - ], - ), - ), - ModeratedSubredditCardInformationWeb(loadedSubreddit: widget.loadedSubreddit), - ], - ), - ], - ); + ), + userName: userName.toString(), + updateData: _loadMore, + data: posts as List, + type: 'community', + ) + : Center( + child: Column( + children: [ + SizedBox( + height: 30.h, + ), + const Icon( + Icons.reddit, + size: 100, + ), + const Text( + 'Wow,such empty', + style: TextStyle(color: Colors.grey), + ) + ], + ), + ); } } - diff --git a/lib/moderated_subreddit/widgets/moderated_subriddet_posts.dart b/lib/moderated_subreddit/widgets/moderated_subriddet_posts.dart deleted file mode 100644 index cfbe9d98..00000000 --- a/lib/moderated_subreddit/widgets/moderated_subriddet_posts.dart +++ /dev/null @@ -1,81 +0,0 @@ -// import 'package:flutter/material.dart'; -// //import 'package:flutter_code_style/analysis_options.yaml'; -// import 'package:responsive_sizer/responsive_sizer.dart'; -// import '../widgets/mod_subreddit_post_sort_bottom.dart'; -// import '../../post/widgets/post.dart'; -// import '../../post/test_data.dart'; -// import 'package:provider/provider.dart'; -// //import 'package:flutter_code_style/analysis_options.yaml'; -// import '../../post/models/post_model.dart'; -// import '../../providers/subreddit_post.dart'; - -// class ModeratedSubriddetPosts extends StatefulWidget { -// final String routeNamePop; -// final String subredditName; - -// ModeratedSubriddetPosts( -// {Key? key, required this.routeNamePop, required this.subredditName}) -// : super(key: key); -// // [ -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'}, -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'}, -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'} -// // ]; -// @override -// State createState() => _ModeratedSubriddetPosts(); -// } - -// class _ModeratedSubriddetPosts extends State { -// bool _isInit = true; -// bool _isLoading = false; -// List? posts = []; -// @override -// void didChangeDependencies() { -// if (_isInit) { -// setState(() { -// _isLoading = true; -// }); -// Provider.of(context, listen: false) -// .fetchNewProfilePosts(widget.subredditName) -// .then((value) { -// posts = Provider.of(context, listen: false) -// .gettingProfilePostData; -// setState(() { -// _isLoading = false; -// }); -// }); -// } -// _isInit = false; -// super.didChangeDependencies(); -// } - -// @override -// Widget build(BuildContext context) { -// return ListView( -// scrollDirection: Axis.vertical, -// children: [ -// ModSubredditPostSortBottom( -// widget.routeNamePop, -// //_dropDownValue, _icon -// ), -// //Select the type of Posts -// SingleChildScrollView( -// child: ListView.builder( -// physics: const ClampingScrollPhysics(), -// shrinkWrap: true, -// itemBuilder: ((context, index) => Post.community( -// data: posts![index], -// )), -// itemCount: posts!.length, -// ), -// ), -// ], -// ); -// } -// } diff --git a/lib/moderated_subreddit/widgets/position_for_moderated_subredditInfo.dart b/lib/moderated_subreddit/widgets/position_for_moderated_subredditInfo.dart index 3026d076..846931ad 100644 --- a/lib/moderated_subreddit/widgets/position_for_moderated_subredditInfo.dart +++ b/lib/moderated_subreddit/widgets/position_for_moderated_subredditInfo.dart @@ -1,11 +1,8 @@ -// ignore_for_file: file_names - import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:post/moderation_settings/screens/moderator_tools_screen.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import '../../models/subreddit_data.dart'; - class PositionForModeratedSubredditInfo extends StatelessWidget { final SubredditData? loadedSubreddit; final String? userName; @@ -32,8 +29,6 @@ class PositionForModeratedSubredditInfo extends StatelessWidget { margin: const EdgeInsets.only(top: 15), width: double.infinity, height: MediaQuery.of(context).size.height * 0.09, - // width: 100.w, - // height: 9.h, child: ListTile( title: Text('r/${loadedSubreddit!.name.toString()}', style: const TextStyle(fontWeight: FontWeight.bold)), @@ -44,8 +39,6 @@ class PositionForModeratedSubredditInfo extends StatelessWidget { margin: const EdgeInsets.only(bottom: 30), width: MediaQuery.of(context).size.width * 0.35, height: MediaQuery.of(context).size.height * 0.04, - // width: 35.w, - // height: 4.h, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( diff --git a/lib/moderation_settings/screens/moderator_tools_screen.dart b/lib/moderation_settings/screens/moderator_tools_screen.dart index ef270e65..1124526b 100644 --- a/lib/moderation_settings/screens/moderator_tools_screen.dart +++ b/lib/moderation_settings/screens/moderator_tools_screen.dart @@ -12,7 +12,7 @@ import './approved_users_screen.dart'; import './banned_user_sceen.dart'; import './muted_user_screen.dart'; import './moderators_screen.dart'; - +import './traffic_state.dart'; class ModeratorTools extends StatefulWidget { /// the route name of the screen @@ -221,6 +221,14 @@ class _ModeratorToolsState extends State { ModalRoute.of(context)?.settings.arguments as String), 'Banned users', Icons.gavel_outlined), + buildGeneralOptions( + context, + () => Navigator.of(context).pushNamed(TraficState.routeName, + arguments: + //'Cooking' + ModalRoute.of(context)?.settings.arguments as String), + 'Traffic Status', + Icons.view_agenda_outlined), ], ), // ), diff --git a/lib/myprofile/models/myprofile_data.dart b/lib/myprofile/models/myprofile_data.dart index c4990771..90ac0c00 100644 --- a/lib/myprofile/models/myprofile_data.dart +++ b/lib/myprofile/models/myprofile_data.dart @@ -1,20 +1,16 @@ class MyProfileData { - //String? id; String? userName; String? email; String? profilePicture; String? profileBackPicture; String? description; String? displayName; - // DateTime? toDayTime; String? createdAt; - //int? numOfDaysInReddit; int? followersCount; int? postKarma; int? commentkarma; MyProfileData( { - //required this.id, required this.userName, required this.email, required this.profilePicture, @@ -22,52 +18,21 @@ class MyProfileData { required this.description, required this.displayName, required this.createdAt, - // required this.numOfDaysInReddit, required this.followersCount, required this.postKarma, required this.commentkarma}); - + // ===================================this function used to===========================================// +//=================to change json to model===========================// MyProfileData.fromJson(Map json) { - // print(json['id'].runtimeType); - // print(json['userName'].runtimeType); - // print(json['email'].runtimeType); - // print(json['profilePicture'].runtimeType); - // print(json['profileBackground'].runtimeType); - // print(json['followersCount'].runtimeType); - // print(json['createdAt'].runtimeType); - // print(json['postKarma'].runtimeType); - // print(json['commentKarma'].runtimeType); - // print(json['description'].runtimeType); - // print('heeee;ssssssssssssssssssssss'); - //id = json['id']; userName = json['userName']; email = json['email']; profilePicture = json['profilePicture']; profileBackPicture = json['profileBackground']; description = json['description']; - displayName = json['userName']; //json['displayName']; + displayName =json['displayName']??''; followersCount = int.parse(json['followersCount'].toString()); createdAt = json['createdAt']; - // numOfDaysInReddit = int.parse(json['numOfDaysInReddit'].toString()); postKarma = int.parse(json['postKarma'].toString()); - // displayName = json['displayName']; commentkarma = int.parse(json['commentKarma'].toString()); } - - Map toJson() { - final Map data = new Map(); - //data['id'] = this.id; - data['userName'] = this.userName; - data['email'] = this.email; - data['profilePicture'] = this.profilePicture; - data['profileBackPicture'] = this.profileBackPicture; - data['description'] = this.description; - data['followersCount'] = this.followersCount; - data['createdAt'] = this.createdAt; - // data['numOfDaysInReddit'] = this.numOfDaysInReddit; - data['postKarma'] = this.postKarma; - data['displayName'] = this.displayName; - data['commentkarma'] = this.commentkarma; - return data; - } } diff --git a/lib/myprofile/models/myprofile_followers_data.dart b/lib/myprofile/models/myprofile_followers_data.dart index f955d92b..a5d65925 100644 --- a/lib/myprofile/models/myprofile_followers_data.dart +++ b/lib/myprofile/models/myprofile_followers_data.dart @@ -11,6 +11,8 @@ class MyProfileFollowersData { required this.karama, required this.isFollowed, }); + // ===================================this function used to===========================================// +//=================to change json to model===========================// MyProfileFollowersData.fromJson(Map json) { profilePicture=json['profilePicture']; userName = json['userName']; diff --git a/lib/myprofile/providers/myprofile_provider.dart b/lib/myprofile/providers/myprofile_provider.dart index 44649750..a6e5dee3 100644 --- a/lib/myprofile/providers/myprofile_provider.dart +++ b/lib/myprofile/providers/myprofile_provider.dart @@ -19,7 +19,8 @@ class MyProfileProvider with ChangeNotifier { List? get gettingMyProfileFollowersData { return followersData; } - + // ===================================this function used to===========================================// +//==================fetch and set date===========================// Future fetchAndSetMyProfile(BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); @@ -34,7 +35,8 @@ class MyProfileProvider with ChangeNotifier { HandleError.handleError(error.toString(), context); } } - + // ===================================this function used to===========================================// +//==================fetch and set date of Followers===========================// Future fetchAndSetFollowersData(BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); diff --git a/lib/myprofile/screens/myprofile_screen.dart b/lib/myprofile/screens/myprofile_screen.dart index b5899bfd..99f39ded 100644 --- a/lib/myprofile/screens/myprofile_screen.dart +++ b/lib/myprofile/screens/myprofile_screen.dart @@ -2,12 +2,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; +import 'package:get/get.dart'; import '../../widgets/loading_reddit.dart'; import '../widgets/myprofile_web.dart'; import '../widgets/myprofile_app.dart'; import '../models/myprofile_data.dart'; import '../providers/myprofile_provider.dart'; - +import '../../home/widgets/custom_upper_bar.dart'; +import '../../home/controller/home_controller.dart'; +import '../../createpost/controllers/posts_controllers.dart'; class MyProfileScreen extends StatefulWidget { static const routeName = '/myprofile'; @@ -22,7 +25,6 @@ class _MyProfileState extends State var _isLoading = false; var _isInit = true; MyProfileData? loadProfile; - //=MyProfileData(userName: 'Zeinab', email:'Zeianb', profilePicture: '', profileBackPicture: '', description: 'My profile', displayName: 'Zeianb', createdAt: '2019-08-24T14:15:22Z', followersCount:1, postKarma: 0, commentkarma: 0); //=============Tab Bar======================// TabController? _controller; List tabs = [ @@ -62,7 +64,8 @@ class _MyProfileState extends State @override void didChangeDependencies() { // TODO: implement didChangeDependencies - // //===============================Fetch subreddit data =======================================// + // ===================================this function used to===========================================// +//==================fetch date for First time===========================// if (_isInit) { setState(() { _isLoading = true; @@ -81,10 +84,18 @@ class _MyProfileState extends State _isInit = false; super.didChangeDependencies(); } - + final HomeController controller = Get.put( + HomeController(), + ); + final PostController controllerForPost = Get.put( + PostController(), + ); @override Widget build(BuildContext context) { return Scaffold( + appBar: ( kIsWeb)?PreferredSize( + preferredSize: Size(700, 60), + child: UpBar(controller: controller, controllerForCreatePost: controllerForPost,)):null, body: _isLoading ? LoadingReddit() : kIsWeb diff --git a/lib/myprofile/screens/user_followers_screen.dart b/lib/myprofile/screens/user_followers_screen.dart index f01d5542..c0b283ba 100644 --- a/lib/myprofile/screens/user_followers_screen.dart +++ b/lib/myprofile/screens/user_followers_screen.dart @@ -16,38 +16,7 @@ class UserFollowersScreen extends StatefulWidget { } class _UserFollowersScreenState extends State { - List? followersData - // = [ - // MyProfileFollowersData( - // profilePicture: - // 'https://media.istockphoto.com/id/1243055987/photo/woman-silhouette-with-sun-in-head-with-copy-space-multiple-exposure-image.jpg?s=612x612&w=is&k=20&c=Nxu72uSlbHMuAiaGv33LITFTPYqagd5rlE1j0J61yyw=', - // userName: 'userName', - // displayName: 'displayName', - // karama: 4, - // isFollowed: true), - // MyProfileFollowersData( - // profilePicture: - // 'https://media.istockphoto.com/id/1243055987/photo/woman-silhouette-with-sun-in-head-with-copy-space-multiple-exposure-image.jpg?s=612x612&w=is&k=20&c=Nxu72uSlbHMuAiaGv33LITFTPYqagd5rlE1j0J61yyw=', - // userName: 'userName', - // displayName: 'displayName', - // karama: 4, - // isFollowed: false), - // MyProfileFollowersData( - // profilePicture: - // 'https://media.istockphoto.com/id/1243055987/photo/woman-silhouette-with-sun-in-head-with-copy-space-multiple-exposure-image.jpg?s=612x612&w=is&k=20&c=Nxu72uSlbHMuAiaGv33LITFTPYqagd5rlE1j0J61yyw=', - // userName: 'userName', - // displayName: 'displayName', - // karama: 4, - // isFollowed: true), - // MyProfileFollowersData( - // profilePicture: - // 'https://media.istockphoto.com/id/1243055987/photo/woman-silhouette-with-sun-in-head-with-copy-space-multiple-exposure-image.jpg?s=612x612&w=is&k=20&c=Nxu72uSlbHMuAiaGv33LITFTPYqagd5rlE1j0J61yyw=', - // userName: 'userName', - // displayName: 'displayName', - // karama: 4, - // isFollowed: false) - // ] - ; + List? followersData; bool _isInit = true; bool _isLoading = false; @override @@ -95,7 +64,6 @@ class _UserFollowersScreenState extends State { Icons.search, size: 30, ), - //border: OutlineInputBorder(), hintText: 'Search for aspecific userName', ), ), @@ -122,7 +90,6 @@ class _UserFollowersScreenState extends State { itemBuilder: ((context, index) => InkWell( child: Container( width: double.infinity, - // height: 15.h, color: const Color.fromARGB(255, 255, 255, 255), child: Column( diff --git a/lib/myprofile/widgets/myprofile_about.dart b/lib/myprofile/widgets/myprofile_about.dart index 380d61fe..41ad8678 100644 --- a/lib/myprofile/widgets/myprofile_about.dart +++ b/lib/myprofile/widgets/myprofile_about.dart @@ -48,7 +48,7 @@ class MyProfileAbout extends StatelessWidget { )), Container( - margin: EdgeInsets.only(right: 10,left: 10,top: 0), + margin: const EdgeInsets.only(right: 10,left: 10,top: 0), width: 100.w, height: (description == null||description == '') ? 0.h diff --git a/lib/myprofile/widgets/myprofile_app.dart b/lib/myprofile/widgets/myprofile_app.dart index f29c138e..c4eb05f8 100644 --- a/lib/myprofile/widgets/myprofile_app.dart +++ b/lib/myprofile/widgets/myprofile_app.dart @@ -39,15 +39,10 @@ class MyProfileApp extends StatelessWidget { elevation: 4, foregroundColor: Colors.white, backgroundColor: Colors.blue, - // innerBoxIsScrolled ? Colors.blue : Colors.white, title: - // Visibility( - // visible: innerBoxIsScrolled, - // child: Text('u/${loadProfile.displayName}', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold)), - //), expandedHeight: (loadProfile.description == null || loadProfile.description == '') ? 54.h @@ -71,7 +66,6 @@ class MyProfileApp extends StatelessWidget { children: [ //Profile back ground Container( - // color: Colors.blue, height: (loadProfile.description == null || loadProfile.description == '') ? 56.5.h @@ -115,7 +109,6 @@ class MyProfileApp extends StatelessWidget { ProfilePosts( routeNamePop: MyProfileScreen.routeName, userName: userName, - //controller: _scrollController, ), ProfileComments(userName: userName), MyProfileAbout( diff --git a/lib/myprofile/widgets/myprofile_card_information_web.dart b/lib/myprofile/widgets/myprofile_card_information_web.dart index f4f41d08..061ac359 100644 --- a/lib/myprofile/widgets/myprofile_card_information_web.dart +++ b/lib/myprofile/widgets/myprofile_card_information_web.dart @@ -17,7 +17,7 @@ class MyProfileCardInformationWeb extends StatelessWidget { decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white), margin: EdgeInsets.only(right: 180, bottom: 25, top: 30), - width: 60.w, + width: 50.w, height: (loadProfile.description == null || loadProfile.description == '') ? 43.h @@ -27,7 +27,6 @@ class MyProfileCardInformationWeb extends StatelessWidget { children: [ //Profile back ground Container( - // color: Colors.blue, height: (loadProfile.description == null || loadProfile.description == '') ? 40.h diff --git a/lib/myprofile/widgets/myprofile_web.dart b/lib/myprofile/widgets/myprofile_web.dart index 0b0de31c..4b7ed34b 100644 --- a/lib/myprofile/widgets/myprofile_web.dart +++ b/lib/myprofile/widgets/myprofile_web.dart @@ -5,6 +5,8 @@ import '../widgets/myprofile_about.dart'; import '../../widgets/myprofile_comment_web.dart'; import '../../widgets/back_to_button.dart'; import '../../widgets/myprofile_post_web.dart'; +import 'package:get/get.dart'; +import '../screens/myprofile_screen.dart'; class MyProfileWeb extends StatelessWidget { MyProfileWeb( @@ -31,8 +33,22 @@ class MyProfileWeb extends StatelessWidget { color: Colors.white, child: _tabBar, )), - floatingActionButton: - BackToTopButton(scrollController: scrollController), + floatingActionButtonLocation: FloatingActionButtonLocation.miniEndFloat, + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pushNamed(MyProfileScreen.routeName, + arguments: loadProfile.userName); + }, + child: Text( + ' Back to top ', + style: TextStyle(color: Colors.white), + ), + style: ElevatedButton.styleFrom( + shape: StadiumBorder(), backgroundColor: Colors.blue), + ), + ), body: isLoading ? const Center( child: Icon( @@ -42,11 +58,13 @@ class MyProfileWeb extends StatelessWidget { ) : TabBarView(controller: controller, children: [ OverviewMyProfileWeb( - type: 'MyProfile', + type: 'MyProfile', loadProfile: loadProfile, scrollController: scrollController), - MyProfilePostWeb( userName: loadProfile.userName.toString()), - MyProfileCommentWeb(scrollController: scrollController,userName: loadProfile.userName.toString()), + MyProfilePostWeb(userName: loadProfile.userName.toString()), + MyProfileCommentWeb( + scrollController: scrollController, + userName: loadProfile.userName.toString()), MyProfileAbout( int.parse(loadProfile.postKarma.toString()), int.parse(loadProfile.commentkarma.toString()), diff --git a/lib/myprofile/widgets/position_in_flex_app_bar_myprofile.dart b/lib/myprofile/widgets/position_in_flex_app_bar_myprofile.dart index 72ea0305..3653773c 100644 --- a/lib/myprofile/widgets/position_in_flex_app_bar_myprofile.dart +++ b/lib/myprofile/widgets/position_in_flex_app_bar_myprofile.dart @@ -64,13 +64,11 @@ class PositionInFlexAppBarMyProfile extends StatelessWidget { color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold), - // style: Theme.of(context).textTheme.headline6, ), )), const SizedBox( height: 10, ), - //username Text( loadProfile.displayName.toString(), style: const TextStyle( @@ -78,7 +76,6 @@ class PositionInFlexAppBarMyProfile extends StatelessWidget { fontWeight: FontWeight.bold, fontSize: 22), ), - // On Click Display all followers of users Container( padding: const EdgeInsets.all(0), alignment: Alignment.bottomLeft, @@ -97,7 +94,6 @@ class PositionInFlexAppBarMyProfile extends StatelessWidget { Text( '${loadProfile.followersCount} followers', style: const TextStyle( - //backgroundColor: Colors.orange, color: Colors.white, fontWeight: FontWeight.bold, fontSize: 13), diff --git a/lib/myprofile/widgets/position_myprofile_web.dart b/lib/myprofile/widgets/position_myprofile_web.dart index 2c59e5b4..b0a550a8 100644 --- a/lib/myprofile/widgets/position_myprofile_web.dart +++ b/lib/myprofile/widgets/position_myprofile_web.dart @@ -19,7 +19,6 @@ class PositionMyProfileWeb extends StatelessWidget { height: 100.h, child: Container( color: Colors.white, - // height: 50.h, padding: const EdgeInsets.only(left: 10, top: 5), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -116,9 +115,6 @@ class PositionMyProfileWeb extends StatelessWidget { //followers Container( padding: const EdgeInsets.all(0), - // alignment: Alignment.bottomLeft, - //color: Colors.amber, - // margin: EdgeInsets.all(30), height: 7.5.h, width: 40.w, child: TextButton( @@ -126,7 +122,6 @@ class PositionMyProfileWeb extends StatelessWidget { .pushNamed(UserFollowersScreen.routeName), style: ButtonStyle( foregroundColor: MaterialStateProperty.all(Colors.black), - // backgroundColor: MaterialStateProperty.all(Colors.black), ), child: Column( mainAxisAlignment: MainAxisAlignment.start, @@ -146,9 +141,7 @@ class PositionMyProfileWeb extends StatelessWidget { Text( '${loadProfile.followersCount} ', style: const TextStyle( - //backgroundColor: Colors.orange, color: Colors.black, - //fontWeight: FontWeight.bold, fontSize: 13), textAlign: TextAlign.justify, ), diff --git a/lib/notification/screens/notifications_main_screen.dart b/lib/notification/screens/notifications_main_screen.dart index dd6ceed9..13b06002 100644 --- a/lib/notification/screens/notifications_main_screen.dart +++ b/lib/notification/screens/notifications_main_screen.dart @@ -114,6 +114,7 @@ class _NotificationsMainScreenState extends State { } _hideThisNotification(notificationId, i) async { + print('Hide notification'); await Provider.of(context, listen: false) .markAndHideThisNotification(context, notificationId, 'hide', i) .then((value) { diff --git a/lib/other_profile/models/moderated_subreddit_user_data.dart b/lib/other_profile/models/moderated_subreddit_user_data.dart index dcbfe931..05179295 100644 --- a/lib/other_profile/models/moderated_subreddit_user_data.dart +++ b/lib/other_profile/models/moderated_subreddit_user_data.dart @@ -4,7 +4,8 @@ class ModeratedSubbredditUserData { ModeratedSubbredditUserData( {required this.icon, required this.subredditName, }); - + // ===================================this function used to===========================================// +//=================to change json to model===========================// ModeratedSubbredditUserData.fromJson(Map json) { icon = json['icon'].toString(); subredditName = json['fixedName'].toString(); diff --git a/lib/other_profile/models/others_profile_data.dart b/lib/other_profile/models/others_profile_data.dart index 774b0256..48827d16 100644 --- a/lib/other_profile/models/others_profile_data.dart +++ b/lib/other_profile/models/others_profile_data.dart @@ -1,62 +1,30 @@ class OtherProfileData { - //String? id; String? userName; String? email; String? profilePicture; String? profileBackPicture; String? description; String? displayName; - // DateTime? toDayTime; String? createdAt; - //int? numOfDaysInReddit; int? followersCount; int? postKarma; int? commentkarma; bool isFollowed = false; OtherProfileData( - { - //required this.id, - required this.userName, + {required this.userName, required this.email, required this.profilePicture, required this.profileBackPicture, required this.description, required this.displayName, required this.createdAt, - //required this.numOfDaysInReddit, required this.followersCount, required this.postKarma, required this.commentkarma, required this.isFollowed}); - -// { -// "id": 10, -// "userName": "Zeinab_maoawad", -// "email": "user@email.com", -// "profilePicture": "https://militaryhealthinstitute.org/wp-content/uploads/sites/37/2019/10/blank-person-icon-9.jpg", -// "profileBackPicture": "https://preview.redd.it/vqqv5xbfezp91.jpg?width=4096&format=pjpg&auto=webp&s=54acda24af01e2de60e98603e3e29e8db381ebac", -// "description": "I'm Student", -// "createdAt": "2022-11-09T00:19:45.186+00:00", -// "followersCount": 0, -// "numOfDaysInReddit": 0, -// "displayName": "Zeinab_maoawad", -// "postKarma": 1, -// "commentkarma": 1, -// "isFollowed": true -// } + // ===================================this function used to===========================================// +//=================to change json to model===========================// OtherProfileData.fromJson(Map json) { - // print(json['id'].runtimeType); - // print(json['userName'].runtimeType); - // print(json['email'].runtimeType); - // print(json['profilePicture'].runtimeType); - // print(json['profileBackground'].runtimeType); - // print(json['followersCount'].runtimeType); - // print(json['createdAt'].runtimeType); - // print(json['postKarma'].runtimeType); - // print(json['commentKarma'].runtimeType); - // print(json['description'].runtimeType); - // print(json['isFollowed'].runtimeType); - //id = json['id'].toString(); userName = json['userName']; email = json['email']; profilePicture = json['profilePicture']; @@ -69,34 +37,4 @@ class OtherProfileData { commentkarma = int.parse(json['commentKarma'].toString()); isFollowed = json['isFollowed']; } - - Map toJson() { - final Map data = new Map(); - //data['id'] = this.id; - data['userName'] = this.userName; - data['email'] = this.email; - data['profilePicture'] = this.profilePicture; - data['profileBackPicture'] = this.profileBackPicture; - data['description'] = this.description; - data['toDayTime'] = this.createdAt; - data['followersCount'] = this.followersCount; - data['toDayTime'] = this.createdAt; - //data['numOfDaysInReddit'] = this.numOfDaysInReddit; - data['postKarma'] = this.postKarma; - data['displayName'] = this.displayName; - data['commentkarma'] = this.commentkarma; - data['isFollowed'] = this.isFollowed; - data['createdAt'] = this.createdAt; - return data; - } } - -// { -// "contentvisibility": true, -// "canbeFollowed": true, -// "lastUpdatedPassword": "2022-10-22-06-12", -// "friendsCount": 0, -// "accountActivated": true, -// "gender": "male", -// "karma": 1 -// } \ No newline at end of file diff --git a/lib/other_profile/providers/other_profile_provider.dart b/lib/other_profile/providers/other_profile_provider.dart index 9c399c03..41df49c1 100644 --- a/lib/other_profile/providers/other_profile_provider.dart +++ b/lib/other_profile/providers/other_profile_provider.dart @@ -17,7 +17,9 @@ class OtherProfileprovider with ChangeNotifier { List? get gettingModeratedSubreddit { return moderatedSubbredditUserData; } - + // ===================================this function used to===========================================// +//==================fetch and set date===========================// +//moderatedSubredditUserName==> userName Of Subreddit Future fetchAndSetOtherProfile( String otherUserName, BuildContext context) async { try { @@ -34,7 +36,8 @@ class OtherProfileprovider with ChangeNotifier { HandleError.handleError(error.toString(), context); } } - + // ===================================this function used to===========================================// +//==================fetch and set date moderated Subreddit of user===========================// Future fetchAndSetModeratedSubredditUser(BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); @@ -55,7 +58,10 @@ class OtherProfileprovider with ChangeNotifier { HandleError.handleError(error.toString(), context); } } - + // ===================================this function used to===========================================// +//==================invite otherusers to my moderated subreddit===========================// +//subredditName=> userName Of Subreddit +//userName=> user who i invite Future invitation( String subredditName, String userName, BuildContext context) async { try { @@ -83,7 +89,9 @@ class OtherProfileprovider with ChangeNotifier { HandleError.handleError(error.toString(), context); return false; } - } + } // ===================================this function used to===========================================// +//==================block otherusers===========================// +//userName=> user who i block Future blockUser(String userName, BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); @@ -99,7 +107,10 @@ class OtherProfileprovider with ChangeNotifier { return false; } } - + // ===================================the next two function used to===========================================// +//==================follow and unfollow otherusers===========================// +//subredditName=> userName Of Subreddit +//userName=> user who i follow/unfollow Future followUser(String userName, BuildContext context) async { try { final prefs = await SharedPreferences.getInstance(); diff --git a/lib/other_profile/screens/others_profile_screen.dart b/lib/other_profile/screens/others_profile_screen.dart index c287f6af..d2e3f666 100644 --- a/lib/other_profile/screens/others_profile_screen.dart +++ b/lib/other_profile/screens/others_profile_screen.dart @@ -2,12 +2,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:post/other_profile/models/others_profile_data.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import 'package:get/get.dart'; import 'package:provider/provider.dart'; import '../../widgets/loading_reddit.dart'; import '../widgets/other_profile_web.dart'; import '../widgets/other_profile_app.dart'; import '../providers/other_profile_provider.dart'; - +import '../../home/widgets/custom_upper_bar.dart'; +import '../../home/controller/home_controller.dart'; +import '../../createpost/controllers/posts_controllers.dart'; class OthersProfileScreen extends StatefulWidget { static const routeName = '/OthersProfileScreen'; @@ -55,12 +58,11 @@ class _OthersProfileScreenState extends State _controller!.dispose(); super.dispose(); } - + // ===================================this function used to===========================================// +//==================fetch date for first time===========================// @override void didChangeDependencies() { // TODO: implement didChangeDependencies - //===============================doing fetch=======================================// - if (_isInit) { setState(() { _isLoading = true; @@ -82,10 +84,18 @@ class _OthersProfileScreenState extends State //==================================================// super.didChangeDependencies(); } - + final HomeController controller = Get.put( + HomeController(), + ); + final PostController controllerForPost = Get.put( + PostController(), + ); @override Widget build(BuildContext context) { return Scaffold( + appBar: ( kIsWeb)?PreferredSize( + preferredSize: Size(700, 60), + child: UpBar(controller: controller, controllerForCreatePost: controllerForPost,)):null, body: _isLoading ? LoadingReddit() : kIsWeb diff --git a/lib/other_profile/widgets/invite_button.dart b/lib/other_profile/widgets/invite_button.dart index 5be4adcb..41312f2a 100644 --- a/lib/other_profile/widgets/invite_button.dart +++ b/lib/other_profile/widgets/invite_button.dart @@ -25,11 +25,9 @@ class InviteButtonState extends State { void initState() { // TODO: implement initState super.initState(); - // textMessage = ''; - // // textMessage = 'Message ${widget.userName}'; - // message = TextEditingController(); } - + // ===================================this function used to===========================================// +//==================fetch date for Moderated Subreddit For User===========================// @override void didChangeDependencies() { // TODO: implement didChangeDependencies @@ -38,7 +36,6 @@ class InviteButtonState extends State { setState(() { _isLoading = true; }); - // print('12 '); Provider.of(context, listen: false) .fetchAndSetModeratedSubredditUser(context) .then((value) { @@ -50,8 +47,6 @@ class InviteButtonState extends State { }); } _isInit = false; - - //==================================================// super.didChangeDependencies(); } @@ -170,19 +165,16 @@ class InviteButtonState extends State { SizedBox( width: 50.w, ), - Icon( + const Icon( Icons.reddit_outlined, color: Colors.deepOrange, size: 50, ), Container( - // color: Colors.amber, height: 6.h, width: 30.w, child: ElevatedButton( style: ButtonStyle( - //shape: Outlin, - side: MaterialStateProperty.all( const BorderSide(color: Colors.white)), shape: MaterialStateProperty.all( @@ -223,7 +215,8 @@ class InviteButtonState extends State { }, ); } - + // ===================================this function used to===========================================// +//==================To Invit Other Users===========================// Future invite(BuildContext context) async { bool invite = await Provider.of(context, listen: false) @@ -238,7 +231,7 @@ class InviteButtonState extends State { } else { ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar( - isError: true, text:'Invitation Faild' , disableStatus: true), + isError: true, text:'Invitation Failed' , disableStatus: true), ); } return false; diff --git a/lib/other_profile/widgets/options_button.dart b/lib/other_profile/widgets/options_button.dart deleted file mode 100644 index 4e8ad010..00000000 --- a/lib/other_profile/widgets/options_button.dart +++ /dev/null @@ -1,96 +0,0 @@ -// import 'package:flutter/material.dart'; -// //import 'package:flutter_code_style/analysis_options.yaml'; -// import 'package:responsive_sizer/responsive_sizer.dart'; -// import './other_profile_card_information_web.dart'; - -// class OptionsButton extends StatefulWidget { -// bool moreOptions; -// OptionsButton({ -// Key? key, -// required this.moreOptions, -// }) : super(key: key); -// @override -// State createState() => _OptionsButtonState(); -// } - -// class _OptionsButtonState extends State { -// void initState() { -// //moreOptions = false; -// super.initState(); -// } - -// @override -// Widget build(BuildContext context) { -// return Positioned( -// top: 340, -// child: Column( -// children: [ -// Visibility( -// visible:OtherProfileCardInformationWeb.moreOptions, -// child: Container( -// child: Column( -// children: [ -// TextButton( -// onPressed: null, -// child: Text( -// 'Send Message', -// style: TextStyle( -// color: Colors.blue, -// fontWeight: FontWeight.bold, -// fontSize: 15), -// )), -// TextButton( -// onPressed: null, -// child: Text( -// 'Block User', -// style: TextStyle( -// color: Colors.blue, -// fontWeight: FontWeight.bold, -// fontSize: 15), -// )), -// TextButton( -// onPressed: null, -// child: Text( -// 'Get Them Help and Support', -// style: TextStyle( -// color: Colors.blue, -// fontWeight: FontWeight.bold, -// fontSize: 15), -// )), -// TextButton( -// onPressed: null, -// child: Text( -// 'Report User', -// style: TextStyle( -// color: Colors.blue, -// fontWeight: FontWeight.bold, -// fontSize: 15), -// )) -// ], -// )), -// ), -// Container( -// width: 15.w, -// height: 6.h, -// child: TextButton( -// onPressed: () { -// setState(() { -// OtherProfileCardInformationWeb.moreOptions= !OtherProfileCardInformationWeb.moreOptions; -// }); -// }, -// style: ButtonStyle( -// // backgroundColor: MaterialStateProperty.all(Colors.blue) -// ), -// child: Text( -// OtherProfileCardInformationWeb.moreOptions? 'More Options' : 'Less Options', -// style: TextStyle( -// color: Colors.blue, -// fontWeight: FontWeight.bold, -// fontSize: 15), -// ), -// )), -// ], -// )); - -// } -// } diff --git a/lib/other_profile/widgets/other_profile_app.dart b/lib/other_profile/widgets/other_profile_app.dart index c9656885..5f7bd595 100644 --- a/lib/other_profile/widgets/other_profile_app.dart +++ b/lib/other_profile/widgets/other_profile_app.dart @@ -39,15 +39,10 @@ class OtherProfileApp extends StatelessWidget { foregroundColor: Colors.white, elevation: 4, backgroundColor:Colors.blue, - // innerBoxIsScrolled?Colors.blue:Colors.white, title: - // Visibility( - // visible: innerBoxIsScrolled, - // child: Text('u/${loadProfile.displayName}', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold)), - //), expandedHeight: (loadProfile.description == null || loadProfile.description == '') ? 54.h @@ -74,7 +69,6 @@ class OtherProfileApp extends StatelessWidget { children: [ //Profile back ground Container( - // color: Colors.blue, height: (loadProfile.description == null || loadProfile.description == '') ? 56.h diff --git a/lib/other_profile/widgets/other_profile_card_information_web.dart b/lib/other_profile/widgets/other_profile_card_information_web.dart index 36d44c56..a2147ba1 100644 --- a/lib/other_profile/widgets/other_profile_card_information_web.dart +++ b/lib/other_profile/widgets/other_profile_card_information_web.dart @@ -28,8 +28,8 @@ class _OtherProfileCardInformationWebState return Expanded( child: Container( margin: const EdgeInsets.only(right: 180, bottom: 25, top: 30), - width: 60.w, - height: widget.moreOptions ? 65.h : 50.h, + width: 50.w, + height: widget.moreOptions ? 80.h : 70.h, color: Colors.white, child: Column(children: [ Stack( @@ -59,10 +59,7 @@ class _OtherProfileCardInformationWebState ), //tomake widget position PositionOtherProfileWeb(loadProfile: widget.loadProfile), - // OptionsButton( - // // moreOptions: OtherProfileCardInformationWeb.moreOptions, - // ), - Positioned( + Positioned( top: 340, child: Column( children: [ @@ -83,7 +80,7 @@ class _OtherProfileCardInformationWebState fontSize: 15), )), TextButton( - onPressed: ()=> _showLeaveDialog(), + onPressed: ()=> _showBlockDialog(), child: const Text( 'Block User', style: TextStyle( @@ -140,8 +137,10 @@ class _OtherProfileCardInformationWebState ]), )); } - - void _showLeaveDialog() { + // ===================================the next three function used to===========================================// +//==================Block user===========================// +// have two option one:blocksubreddit two: cancel + void _showBlockDialog() { showDialog( context: context, builder: (ctx) => AlertDialog( @@ -186,7 +185,7 @@ class _OtherProfileCardInformationWebState ), ), Container( - width: 35.w, + width: 15.w, height: 6.h, child: ElevatedButton( style: ButtonStyle( @@ -206,13 +205,13 @@ class _OtherProfileCardInformationWebState if (!block) { ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar( isError: false, - text: 'Invitation Successfully', + text: 'Block Successfully', disableStatus: true)); } else { ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar( isError: false, - text: 'Invitation Successfully', + text: 'Block Failed', disableStatus: true), ); } diff --git a/lib/other_profile/widgets/other_profile_web.dart b/lib/other_profile/widgets/other_profile_web.dart index c172b5bc..bb098298 100644 --- a/lib/other_profile/widgets/other_profile_web.dart +++ b/lib/other_profile/widgets/other_profile_web.dart @@ -5,7 +5,7 @@ import '../widgets/others_profile_about.dart'; import '../../widgets/myprofile_comment_web.dart'; import '../../widgets/back_to_button.dart'; import '../../widgets/myprofile_post_web.dart'; - +import '../screens/others_profile_screen.dart'; class OtherProfileWeb extends StatelessWidget { OtherProfileWeb( {Key? key, @@ -31,8 +31,22 @@ class OtherProfileWeb extends StatelessWidget { color: Colors.white, child: _tabBar, )), - floatingActionButton: - BackToTopButton(scrollController: scrollController), + floatingActionButtonLocation: FloatingActionButtonLocation.miniEndFloat, + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pushNamed(OthersProfileScreen.routeName, + arguments: loadProfile.userName); + }, + child: Text( + ' Back to top ', + style: TextStyle(color: Colors.white), + ), + style: ElevatedButton.styleFrom( + shape: StadiumBorder(), backgroundColor: Colors.blue), + ), + ), body: isLoading ? const Center( child: Icon( diff --git a/lib/other_profile/widgets/others_profile_about.dart b/lib/other_profile/widgets/others_profile_about.dart index 8887951b..8c80d83c 100644 --- a/lib/other_profile/widgets/others_profile_about.dart +++ b/lib/other_profile/widgets/others_profile_about.dart @@ -6,14 +6,8 @@ class OthersProfileAbout extends StatelessWidget { final int numOfPosts; final int numOfComments; - - // final int numOfAwarder; - - // final int numOfAwardee; final String description; - OthersProfileAbout(this.numOfPosts, this.numOfComments, - // this.numOfAwarder, - // this.numOfAwardee, + OthersProfileAbout(this.numOfPosts, this.numOfComments, this.description); @override Widget build(BuildContext context) { @@ -22,7 +16,6 @@ class OthersProfileAbout extends StatelessWidget { children: [ Container( padding: const EdgeInsets.only(top: 120), - // height: 32.h, height: (description == null||description == '') ? 36.h : (36 + (description.length / 42) + 4).h, @@ -51,28 +44,8 @@ class OthersProfileAbout extends StatelessWidget { ), ], )), - // Expanded( - // child: Row( - // children: [ - // Expanded( - // child: ListTile( - // title: Text('$numOfAwarder'), - // subtitle: const Text('Awarder Karma'), - // ), - // ), - // Expanded( - // child: ListTile( - // title: Text('$numOfAwardee'), - // subtitle: const Text('Awardee Karma'), - // ), - // ) - // ], - // ), - // ), Container( - //color: Colors.lightBlue, - // padding: EdgeInsets.all(20), - margin: EdgeInsets.only(right: 15,left: 15,top: 15), + margin: const EdgeInsets.only(right: 15,left: 15,top: 15), width: 100.w, height: (description == null||description == '') ? 0.h @@ -89,7 +62,7 @@ class OthersProfileAbout extends StatelessWidget { ]), ), ListTile( - leading: Icon( + leading: const Icon( size: 25, Icons.local_post_office_outlined, color: Colors.grey, @@ -106,39 +79,6 @@ class OthersProfileAbout extends StatelessWidget { ), ]), ), - // Container( - // padding: const EdgeInsets.all(10), - // // height: MediaQuery.of(context).size.height * 0.05, - // // width: MediaQuery.of(context).size.height * 1, - // height: 5.h, - // width: 100.h, - // child: const Text( - // 'TROPHIES', - // textAlign: TextAlign.start, - // style: TextStyle(color: Color.fromARGB(255, 134, 133, 133)), - // )), - // Container( - // padding: const EdgeInsets.only(bottom: 10, top: 100), - // height: 100.h, - // width: 100.h, - // color: Colors.white, - // child: Column(children: [ - // Expanded( - // child: Row( - // children: const [ - // Expanded( - // child: ListTile( - // title: Text(''), - // subtitle: Text( - // '', - // ), - // ), - // ), - // ], - // ), - // ) - // ]), - // ), ], ); } diff --git a/lib/other_profile/widgets/overview_other_profile_web.dart b/lib/other_profile/widgets/overview_other_profile_web.dart index 8dcb6d34..fe92e0d0 100644 --- a/lib/other_profile/widgets/overview_other_profile_web.dart +++ b/lib/other_profile/widgets/overview_other_profile_web.dart @@ -1,80 +1,168 @@ import 'package:flutter/material.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; +import 'package:provider/provider.dart'; import '../../widgets/sort_bottom_web.dart'; import '../models/others_profile_data.dart'; import '../widgets/other_profile_card_information_web.dart'; +import '../../providers/profile_provider.dart'; +import '../../widgets/loading_reddit.dart'; +import '../../widgets/sort_bottom_web.dart'; +import '../../post/widgets/post_comment_list.dart'; class OverviewOtherProfileWeb extends StatefulWidget { final OtherProfileData loadProfile; - final ScrollController scrollController; - OverviewOtherProfileWeb({ + final ScrollController scrollController; + OverviewOtherProfileWeb({ Key? key, - required this.scrollController, + required this.scrollController, required this.loadProfile, }) : super(key: key); // Posts(this.routeNamePop); @override - State createState() => _OverviewOtherProfileWebState(); + State createState() => + _OverviewOtherProfileWebState(); } class _OverviewOtherProfileWebState extends State { + int _page = 1; + final int _limit = 25; + bool _isInit = true; + bool _isLoading = false; + bool _isLoadMoreRunning = false; + List>? commentsAndPosts; + String dateOfcomment(String date) { + final data1 = DateTime.parse(date); + final date2 = DateTime.now(); + final difference = date2.difference(data1); + final differenceMonth = date2.month - data1.month; + final differenceYear = date2.year - data1.year; + + if (difference.inHours < 24) { + return '${difference.inHours}h'; + } else if (difference.inDays < 30) { + final numOfWeeks = difference.inDays ~/ 7; + if (numOfWeeks > 0) { + return '${numOfWeeks}w'; + } else { + return '${difference.inDays}d'; + } + } else if (differenceYear > 0) { + return '${differenceYear}y'; + } else { + return '${differenceMonth}mon'; + } + } + + ScrollController _scrollController = new ScrollController(); + void _loadMore() { + if (_isLoading == false && _isLoadMoreRunning == false) { + setState(() { + toggleLoadingMore(); // Display a progress indicator at the bottom + }); + setState(() { + _page += 1; + }); + // Increase _page by + + setState(() { + toggleLoadingMore(); + }); + } + } + + bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; + + @override + void initState() { + // TODO: implement initState + super.initState(); + _scrollController = ScrollController()..addListener(_loadMore); + } + // ===================================this function used to===========================================// +//==================fetch date for first time===========================// + @override + Future didChangeDependencies() async { + // TODO: implement didChangeDependencies + if (_isInit) { + setState(() { + _isLoading = true; + }); + //New Hot Top + await Provider.of(context, listen: false) + .fetchandSetProfilePostsAndComments( + widget.loadProfile.userName.toString(), + 'New', + _page, + _limit, + context) + .then((value) async { + commentsAndPosts = + await Provider.of(context, listen: false) + .gettingPostCommentData; + setState(() { + _isLoading = false; + }); + }); + } + _isInit = false; + super.didChangeDependencies(); + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { - return ListView( - scrollDirection: Axis.vertical, - controller: widget.scrollController, - children: [ - Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - flex: 2, - child: Column( - children: [ - // SizedBox(height: 4.h,), - Container( - height: 6.h, - width: 50.w, - margin: EdgeInsets.only(left: 100, bottom: 10, top: 30), - child: SortBottomWeb(page: 1 ,userName: widget.loadProfile.userName.toString()), - color: Colors.white, - // width: 100.w, - ), - Container( - // padding: const EdgeInsets.only(bottom: 100,), - margin: EdgeInsets.only(left: 100, bottom: 90, top: 30), - height: 30.h, - width: 50.w, - // color: Colors.white, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: const [ - Expanded( - child: ListTile( - title: Text('Post'), - ), - ), - ], - ), - ) - ]), + commentsAndPosts = Provider.of(context, listen: true) + .gettingPostCommentData; + return (_isLoading || _isLoadMoreRunning) + ? const LoadingReddit() + : (commentsAndPosts == null || commentsAndPosts!.isEmpty) + ? Center( + child: Column( + children: [ + SizedBox( + height: 30.h, + ), + const Icon( + Icons.reddit, + size: 100, + color: Colors.black, + ), + const Text( + 'Wow,such empty', + style: TextStyle(color: Colors.grey), + ) + ], + ), + ) + : PostCommentList( + leftMargin: 15.w, + rightMargin: 35.w, + topOfTheList: Container( + height: 80.h, + width: 50.h, + margin: EdgeInsets.only(left: 15.w), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + OtherProfileCardInformationWeb( + loadProfile: widget.loadProfile), + SortBottomWeb( + page: 1, + userName: widget.loadProfile.userName.toString()), + ], ), - ], - ), - ), - OtherProfileCardInformationWeb(loadProfile: widget.loadProfile), - ], - ), - ], - ); + ), + userName: widget.loadProfile.userName.toString(), + updateData: _loadMore, + data: commentsAndPosts as List>, + type: 'Profile', + ); } } diff --git a/lib/other_profile/widgets/pop_down_menu.dart b/lib/other_profile/widgets/pop_down_menu.dart index a57e5f6d..5fe3a1c1 100644 --- a/lib/other_profile/widgets/pop_down_menu.dart +++ b/lib/other_profile/widgets/pop_down_menu.dart @@ -71,7 +71,7 @@ class _PopDownMenuState extends State { color: Colors.black, ), onTap: () { - _showLeaveDialog(); + _showBlockDialog(); }, title: const Text( 'Block account', @@ -94,8 +94,10 @@ class _PopDownMenuState extends State { ), ]); } - - void _showLeaveDialog() { + // ===================================the next three function used to===========================================// +//==================Block user===========================// +// have two option one:blocksubreddit two: cancel + void _showBlockDialog() { showDialog( context: context, builder: (ctx) => AlertDialog( diff --git a/lib/other_profile/widgets/position_other_profile_web.dart b/lib/other_profile/widgets/position_other_profile_web.dart index 912d7445..deccd4b6 100644 --- a/lib/other_profile/widgets/position_other_profile_web.dart +++ b/lib/other_profile/widgets/position_other_profile_web.dart @@ -3,6 +3,7 @@ import 'package:responsive_sizer/responsive_sizer.dart'; import '../models/others_profile_data.dart'; import 'package:provider/provider.dart'; import '../providers/other_profile_provider.dart'; +import 'package:intl/intl.dart'; import '../../widgets/custom_snack_bar.dart'; class PositionOtherProfileWeb extends StatefulWidget { PositionOtherProfileWeb({ @@ -14,13 +15,14 @@ class PositionOtherProfileWeb extends StatefulWidget { @override State createState() => - _PositionOtherProfileWebState(); + PositionOtherProfileWebState(); } -class _PositionOtherProfileWebState extends State { +class PositionOtherProfileWebState extends State { bool moreOptions = false; bool isFollowedstate = false; - + // ===================================the next two function used to===========================================// +//==================To follow users===========================// void _follow() async { bool follow = await Provider.of(context, listen: false) @@ -45,7 +47,8 @@ class _PositionOtherProfileWebState extends State { isFollowedstate = true; return isFollowedstate; } - + // ===================================the next two function used to===========================================// +//==================To unfollow users===========================// void _unFollow() async { bool unfollow = await Provider.of(context, listen: false) @@ -65,7 +68,6 @@ class _PositionOtherProfileWebState extends State { ); } } - bool unFollowsucceeded() { isFollowedstate = false; return isFollowedstate; @@ -82,11 +84,9 @@ class _PositionOtherProfileWebState extends State { top: 100, height: 100.h, child: Container( - // width: 100.w, height: 100.h, - - padding: EdgeInsets.only(left: 20, top: 15), - margin: EdgeInsets.only(top: 10), + padding: const EdgeInsets.only(left: 20, top: 15), + margin: const EdgeInsets.only(top: 10), color: Colors.white, child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -109,7 +109,6 @@ class _PositionOtherProfileWebState extends State { ), //name and discibtions Text( - // ${loadProfile.numOfDaysInReddit} .${int.parse(loadProfile.postKarma.toString()) + int.parse(loadProfile.commentkarma.toString())}.${loadProfile.createdAt.toString()} 'u/${widget.loadProfile.displayName}', style: const TextStyle( color: Colors.black, @@ -138,18 +137,17 @@ class _PositionOtherProfileWebState extends State { height: 7, ), Row( - //mainAxisAlignment: MainAxisAlignment, children: [ Column( children: [ - Text('Karma', - style: const TextStyle( + const Text('Karma', + style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 13)), Row( children: [ - Icon( + const Icon( Icons.settings, color: Colors.blue, ), @@ -168,18 +166,18 @@ class _PositionOtherProfileWebState extends State { ), Column( children: [ - Text('CakeDay', - style: const TextStyle( + const Text('CakeDay', + style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 13)), Row( children: [ - Icon( + const Icon( Icons.cake, color: Colors.blue, ), - Text('${widget.loadProfile.createdAt.toString()}', + Text('${DateFormat.yMMMMd('en_US').format(DateTime.parse(widget.loadProfile.createdAt.toString()))}', style: const TextStyle( color: Colors.black, fontWeight: FontWeight.normal, @@ -200,9 +198,6 @@ class _PositionOtherProfileWebState extends State { child: ElevatedButton( onPressed:()=> (isFollowedstate) ? _unFollow() : _follow(), style: ButtonStyle( - // side: MaterialStateProperty.all( - // const BorderSide( - // color: Colors.white)), shape: MaterialStateProperty.all( const RoundedRectangleBorder( borderRadius: @@ -211,54 +206,12 @@ class _PositionOtherProfileWebState extends State { foregroundColor: MaterialStateProperty.all(Colors.white)), child: Text( isFollowedstate ? 'Following' : 'Follow', - style: TextStyle( + style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 15), ), )), - // Visibility( - // visible: moreOptions, - // child: Container( - // child: Column( - // children: [ - // TextButton(onPressed: null, child: Text('Send Message')), - // TextButton(onPressed: null, child: Text('Block User')), - // TextButton( - // onPressed: null, - // child: Text('Get Them Help and Support')), - // TextButton(onPressed: null, child: Text('Report User')) - // ], - // )), - // ), - // Container( - // width: 15.w, - // height: 6.h, - // child: TextButton( - // onPressed: () { - // setState(() { - // moreOptions = true; - // }); - // }, - // style: ButtonStyle( - // // side: MaterialStateProperty.all( - // // const BorderSide( - // // color: Colors.white)), - // shape: MaterialStateProperty.all( - // const RoundedRectangleBorder( - // borderRadius: - // BorderRadius.all(Radius.circular(30)))), - // backgroundColor: MaterialStateProperty.all(Colors.blue), - // foregroundColor: MaterialStateProperty.all(Colors.white)), - // child: Text( - // moreOptions ? 'More Options' : 'Less Options', - // style: TextStyle( - // color: Colors.white, - // fontWeight: FontWeight.bold, - // fontSize: 15), - // ), - // )), - const SizedBox( height: 7, ) diff --git a/lib/post/models/post_model.dart b/lib/post/models/post_model.dart index ff172d48..f84d6f0a 100644 --- a/lib/post/models/post_model.dart +++ b/lib/post/models/post_model.dart @@ -154,24 +154,24 @@ class PostModel { print(json['url'].runtimeType); sId = json['_id']; - ownerType = json['ownerType']; + ownerType = json['ownerType'] ?? 'Subreddit'; replies = json['replies']; - title = json['title']; - kind = json['kind']; - text = json['text']; - images = json['images']; - createdAt = json['createdAt']; + title = json['title'] ?? ''; + kind = json['kind'] ?? 'self'; + text = json['text'] ?? ''; + images = json['images'] ?? []; + createdAt = json['createdAt'] ?? '2017-07-21T17:32:28Z'; locked = json['locked'] ?? false; isDeleted = json['isDeleted'] ?? false; sendReplies = json['sendReplies'] ?? false; nsfw = json['nsfw'] ?? false; spoiler = json['spoiler'] ?? false; - votes = json['votes']; - views = json['views']; - commentCount = json['commentCount']; - shareCount = json['shareCount']; - suggestedSort = json['suggestedSort']; - scheduled = json['scheduled']; + votes = json['votes'] ?? 0; + views = json['views'] ?? 0; + commentCount = json['commentCount'] ?? 0; + shareCount = json['shareCount'] ?? 0; + suggestedSort = json['suggestedSort'] ?? ''; + scheduled = json['scheduled'] ?? false; flairId = json['flairId'] != null ? new FlairId.fromJson(json['flairId']) : null; isHidden = json['isHidden'] ?? false; diff --git a/lib/post/screens/post_screen.dart b/lib/post/screens/post_screen.dart index 9656a2db..fcffab8a 100644 --- a/lib/post/screens/post_screen.dart +++ b/lib/post/screens/post_screen.dart @@ -1,10 +1,13 @@ //import 'package:animated_tree_view/animated_tree_view.dart'; import 'package:flutter/material.dart'; -import 'package:post/comments/models/comment_model.dart'; -import 'package:post/comments/providers/comments_provider.dart'; +import 'package:post/post/widgets/post_list.dart'; +import 'package:post/widgets/loading_reddit.dart'; import 'package:provider/provider.dart'; +import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:video_player/video_player.dart'; import '../../comments/widgets/comment.dart'; +import '../../providers/Profile_provider.dart'; +import '../models/post_model.dart'; class PostScreen extends StatefulWidget { static const routeName = '/post'; @@ -23,20 +26,19 @@ class _PostScreenState extends State { late VideoPlayerController controller1; bool _isInit = true; bool _isLoading = false; - List? commentsData = []; + List? posts = []; @override void didChangeDependencies() { - Provider test; if (_isInit) { setState(() { _isLoading = true; }); - Provider.of(context, listen: false) - .fetchPostComments('s', 1, 2) + Provider.of(context, listen: false) + .fetchProfilePosts('Amr', 'Hot', 1, 25, context) .then((value) { - commentsData = Provider.of(context, listen: false) - .gettingPostComments; + posts = Provider.of(context, listen: false) + .gettingProfilePostData; setState(() { _isLoading = false; }); @@ -97,8 +99,10 @@ class _PostScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(), - body: SingleChildScrollView( + appBar: AppBar(), + body: Center( + child: Container( + width: 40.w, child: Column( children: [ // Post.home( @@ -106,10 +110,14 @@ class _PostScreenState extends State { // inView: false, // userName: 'Amr', // ) - Comment( - data: commentsData![0], - userName: 'Amr', - ), + _isLoading + ? LoadingReddit() + : Container( + child: PostList( + userName: 'Amr', + updateData: updateData, + data: posts as List), + ) // Comment( // data: commentsData![2], // userName: 'Amr', @@ -180,6 +188,8 @@ class _PostScreenState extends State { // ), ], ), - )); + ), + ), + ); } } diff --git a/lib/post/widgets/post.dart b/lib/post/widgets/post.dart index 898e60d4..eb6a0339 100644 --- a/lib/post/widgets/post.dart +++ b/lib/post/widgets/post.dart @@ -12,13 +12,18 @@ import './post_body.dart'; /// This is the main post Widget. /// -/// It takes a map of the post data. class Post extends StatefulWidget { + /// The data of the post final PostModel data; bool _inHome = false, _inProfile = false; //final Function updateDate; + /// A boolean to check if in view final bool inView; + + /// The user name final String userName; + + /// a boolean to determine if in the post screen final bool inScreen; /// This is the constructor for home page. @@ -70,11 +75,10 @@ class _PostState extends State { @override void didChangeDependencies() async { - // TODO: implement didChangeDependencies if (widget.data.isModerator == null && widget.data.ownerType == 'Subreddit') { final provider = - await Provider.of(context, listen: false); + Provider.of(context, listen: false); await provider .getUser( widget.data.owner?.name as String, UserCase.moderator, context) @@ -83,8 +87,6 @@ class _PostState extends State { for (var mod in moderators!) { widget.data.isModerator = false; - print('=============Is mod:${mod.userName}======================='); - if (mod.userName == widget.userName) { widget.data.isModerator = true; break; @@ -109,7 +111,7 @@ class _PostState extends State { // imageNumber: data.imageNumber, // ); return widget.data.isDeleted ?? false - ? SizedBox() + ? const SizedBox() : Container( margin: const EdgeInsetsDirectional.only(bottom: 10), child: Column( @@ -137,6 +139,7 @@ class _PostState extends State { data: data, ), PostFooter( + userName: widget.userName, inScreen: widget.inScreen, data: widget.data, isMyPost: (widget.data.author?.name == widget.userName), diff --git a/lib/post/widgets/post_body.dart b/lib/post/widgets/post_body.dart index 6084c7d5..1110854b 100644 --- a/lib/post/widgets/post_body.dart +++ b/lib/post/widgets/post_body.dart @@ -1,12 +1,18 @@ import 'package:flutter/material.dart'; +import 'package:html/parser.dart'; import 'package:post/post/models/post_model.dart'; import 'package:post/post/widgets/post_card.dart'; import 'package:post/post/widgets/post_images.dart'; +import 'package:post/post/widgets/post_images_web.dart'; +import 'package:post/post/widgets/post_link_in_screen.dart'; import 'package:post/post/widgets/post_tags_and_title.dart'; +import 'package:post/post/widgets/post_video_in_widget_web.dart'; import 'package:video_player/video_player.dart'; import '../../show_post/screens/show_post.dart'; +import '../../show_post/screens/show_post_web.dart'; import 'post_video_in_widget.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; /// This Widget is responsible for the body of the post. @@ -29,10 +35,23 @@ class _PostBodyState extends State { @override Widget build(BuildContext context) { return Flexible( - child: GestureDetector( + child: InkWell( onTap: () { - Navigator.of(context).pushNamed(ShowPostDetails.routeName, - arguments: {'data': widget.data, 'userName': widget.userName}); + kIsWeb + ? Navigator.of(context).pushNamed(ShowPostDetailsWeb.routeName, + arguments: {'data': widget.data, 'userName': widget.userName}) + // ? showDialog( + // context: context, + // builder: (context) => PostPopUpWeb( + // data: widget.data, + // userName: widget.userName, + // ), + // ) + : Navigator.of(context).pushNamed(ShowPostDetails.routeName, + arguments: { + 'data': widget.data, + 'userName': widget.userName + }); }, child: Container( color: (widget.data.isSpam ?? false) @@ -54,55 +73,89 @@ class _PostBodyState extends State { title: widget.data.title as String, ), ), - - // Container( - // padding: const EdgeInsetsDirectional.only( - // start: 10, end: 10, top: 10), - // child: Text( - // widget.data.text as String, - // maxLines: 3, - // style: TextStyle( - // color: Theme.of(context).colorScheme.secondary, - // fontSize: 12, - // ), - // textAlign: TextAlign.start, - // overflow: TextOverflow.ellipsis, - // ), - // ), + Container( + padding: const EdgeInsetsDirectional.only( + start: 10, end: 10, top: 10), + child: Text( + parse(widget.data.text as String) + .documentElement + ?.text ?? + '', + maxLines: 3, + style: TextStyle( + color: Theme.of(context).colorScheme.secondary, + fontSize: 12, + ), + textAlign: TextAlign.start, + overflow: TextOverflow.ellipsis, + ), + ), ], ) : (widget.data.kind == 'image') - ? PostImages( - data: widget.data, - flair: widget.data.flairId, - nsfw: widget.data.nsfw as bool, - spoiler: widget.data.spoiler as bool, - title: widget.data.title as String, - imageNumber: widget.data.imageNumber, - links: widget.data.images!.cast(), - maxHeightImageSize: - widget.data.maxHeightImageSize as Size, - ) - : (widget.data.kind == 'link') - ? PostCard( + ? kIsWeb + ? PostImagesWeb( + data: widget.data, flair: widget.data.flairId, nsfw: widget.data.nsfw as bool, spoiler: widget.data.spoiler as bool, - link: widget.data.url as String, title: widget.data.title as String, - type: widget.data.kind as String, + imageNumber: widget.data.imageNumber, + links: widget.data.images!.cast(), + maxHeightImageSize: + widget.data.maxHeightImageSize as Size, ) - : (widget.data.kind == 'video') - ? PostVideoInWidget( + : PostImages( + data: widget.data, + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + title: widget.data.title as String, + imageNumber: widget.data.imageNumber, + links: widget.data.images!.cast(), + maxHeightImageSize: + widget.data.maxHeightImageSize as Size, + ) + : (widget.data.kind == 'link') + ? kIsWeb + ? PostLinkInScreen( + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + link: widget.data.url as String, title: widget.data.title as String, + type: widget.data.kind as String, + ) + : PostCard( flair: widget.data.flairId, nsfw: widget.data.nsfw as bool, spoiler: widget.data.spoiler as bool, - inView: widget.inView, - url: widget.data.video as String, - videoController: widget.data.videoController - as VideoPlayerController, + link: widget.data.url as String, + title: widget.data.title as String, + type: widget.data.kind as String, ) + : (widget.data.kind == 'video') + ? kIsWeb + ? PostVideoInWidgetWeb( + title: widget.data.title as String, + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + inView: widget.inView, + url: widget.data.video as String, + videoController: widget.data.videoController + as VideoPlayerController, + ) + : PostVideoInWidget( + title: widget.data.title as String, + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + inView: widget.inView, + url: widget.data.video as String, + videoController: widget.data.videoController + as VideoPlayerController, + ) : const SizedBox(), ), ), diff --git a/lib/post/widgets/post_body_in_screen.dart b/lib/post/widgets/post_body_in_screen.dart index a919fa4a..28351b38 100644 --- a/lib/post/widgets/post_body_in_screen.dart +++ b/lib/post/widgets/post_body_in_screen.dart @@ -1,17 +1,24 @@ import 'package:flutter/material.dart'; import 'package:post/post/models/post_model.dart'; -import 'package:post/post/widgets/post_images.dart'; +import 'package:post/post/widgets/post_images_in_screen.dart'; import 'package:post/post/widgets/post_link_in_screen.dart'; import 'package:post/post/widgets/post_tags_and_title.dart'; +import 'package:post/post/widgets/post_video_in_widget_web.dart'; import 'package:video_player/video_player.dart'; import 'post_video_in_widget.dart'; import 'package:flutter_html/flutter_html.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; /// This Widget is responsible for the body of the post. class PostBodyInScreen extends StatefulWidget { + /// The data of the post final PostModel data; + + /// The user name final String userName; + + /// a boolean to check if in screen final bool inView; const PostBodyInScreen( @@ -62,7 +69,7 @@ class _PostBodyInScreenState extends State { ], ) : (widget.data.kind == 'image') - ? PostImages( + ? PostImagesInScreen( data: widget.data, flair: widget.data.flairId, nsfw: widget.data.nsfw as bool, @@ -70,8 +77,7 @@ class _PostBodyInScreenState extends State { title: widget.data.title as String, imageNumber: widget.data.imageNumber, links: widget.data.images!.cast(), - maxHeightImageSize: - widget.data.maxHeightImageSize as Size, + maxHeightImageSize: widget.data.maxHeightImageSize as Size, ) : (widget.data.kind == 'link') ? PostLinkInScreen( @@ -83,16 +89,27 @@ class _PostBodyInScreenState extends State { type: widget.data.kind as String, ) : (widget.data.kind == 'video') - ? PostVideoInWidget( - title: widget.data.title as String, - flair: widget.data.flairId, - nsfw: widget.data.nsfw as bool, - spoiler: widget.data.spoiler as bool, - inView: widget.inView, - url: widget.data.video as String, - videoController: widget.data.videoController - as VideoPlayerController, - ) + ? kIsWeb + ? PostVideoInWidgetWeb( + title: widget.data.title as String, + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + inView: widget.inView, + url: widget.data.video as String, + videoController: widget.data.videoController + as VideoPlayerController, + ) + : PostVideoInWidget( + title: widget.data.title as String, + flair: widget.data.flairId, + nsfw: widget.data.nsfw as bool, + spoiler: widget.data.spoiler as bool, + inView: widget.inView, + url: widget.data.video as String, + videoController: widget.data.videoController + as VideoPlayerController, + ) : const SizedBox(), ), ); diff --git a/lib/post/widgets/post_card.dart b/lib/post/widgets/post_card.dart index 10e39d56..a7683227 100644 --- a/lib/post/widgets/post_card.dart +++ b/lib/post/widgets/post_card.dart @@ -43,11 +43,11 @@ class PostCard extends StatelessWidget { height: 80, child: LinkPreviewGenerator( showDescription: false, - link: 'https://github.com/ghpranav/link_preview_generator', - placeholderWidget: LoadingReddit(), + link: link, + placeholderWidget: const LoadingReddit(), backgroundColor: Colors.black.withOpacity(0.6), showTitle: false, - domainStyle: TextStyle(color: Colors.white, fontSize: 12), + domainStyle: const TextStyle(color: Colors.white, fontSize: 12), ), ), ], diff --git a/lib/post/widgets/post_comment_list.dart b/lib/post/widgets/post_comment_list.dart new file mode 100644 index 00000000..331ae588 --- /dev/null +++ b/lib/post/widgets/post_comment_list.dart @@ -0,0 +1,178 @@ +import 'package:flutter/material.dart'; +import 'package:fluttericon/typicons_icons.dart'; +import 'package:inview_notifier_list/inview_notifier_list.dart'; +import './post.dart'; + +/// A margin to the left of the posts and comments + +class PostCommentList extends StatefulWidget { + /// The user name + + final String userName; + + /// A widget to be displayed above the posts + + final Widget topOfTheList; + + /// A function which is invoked when the CustomScrollView reaches the end + + final Function updateData; + + /// The list of posts and comments' data to be displayed + + final List> data; + + /// A margin to the left of the posts + + final double leftMargin; + + /// A margin to the right of the posts + + final double rightMargin; + + final String type; + const PostCommentList({ + super.key, + required this.userName, + this.topOfTheList = const SizedBox(), + required this.updateData, + required this.data, + this.type = 'home', + this.leftMargin = 0, + this.rightMargin = 0, + }); + + @override + State createState() => _PostCommentListState(); +} + +class _PostCommentListState extends State { + String dateOfcomment(String date) { + final data1 = DateTime.parse(date); + final date2 = DateTime.now(); + final difference = date2.difference(data1); + final differenceMonth = date2.month - data1.month; + final differenceYear = date2.year - data1.year; + + if (difference.inHours < 24) { + return '${difference.inHours}h'; + } else if (difference.inDays < 30) { + final numOfWeeks = difference.inDays ~/ 7; + if (numOfWeeks > 0) { + return '${numOfWeeks}w'; + } else { + return '${difference.inDays}d'; + } + } else if (differenceYear > 0) { + return '${differenceYear}y'; + } else { + return '${differenceMonth}mon'; + } + } + + @override + Widget build(BuildContext context) { + return Flexible( + child: InViewNotifierCustomScrollView( + physics: const AlwaysScrollableScrollPhysics(), + shrinkWrap: true, + onListEndReached: () => widget.updateData(), + scrollDirection: Axis.vertical, + initialInViewIds: const ['0'], + isInViewPortCondition: + (double deltaTop, double deltaBottom, double viewPortDimension) { + return deltaTop < (0.5 * viewPortDimension) && + deltaBottom > (0.5 * viewPortDimension); + }, + slivers: [ + // Container(), + SliverList( + delegate: SliverChildBuilderDelegate( + childCount: 1, + (context, index) => widget.topOfTheList, + ), + ), + SliverList( + delegate: SliverChildBuilderDelegate(childCount: widget.data.length, + (context, index) { + return Container( + margin: EdgeInsetsDirectional.only( + start: widget.leftMargin, end: widget.rightMargin), + child: InViewNotifierWidget( + id: '$index', + builder: (context, isInView, child) { + if (widget.data[index]['type'] == 'comment') { + return Container( + color: Colors.white, + margin: const EdgeInsetsDirectional.only( + top: 10, bottom: 10), + child: ListTile( + title: Text( + widget.data[index]['data'].title.toString()), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Text.rich( + TextSpan( + children: [ + TextSpan( + text: + '${(widget.data[index]['data'].ownerType == 'User') ? 'u/' : 'r/'}${widget.data[index]['data'].owner}.${dateOfcomment(widget.data[index]['data'].createdAt.toString())} .${widget.data[index]['data'].votes}'), + const WidgetSpan( + child: Icon( + Typicons.up, + size: 15, + )), + ], + ), + ), + Text( + widget.data[index]['data'].text.toString()), + ], + ), + ), + ); + } else { + if (widget.type == 'profile') { + return Post.profile( + userName: widget.userName, + inView: isInView, + data: widget.data[index]['data'], + ); + } else if (widget.type == 'community') { + return Post.community( + userName: widget.userName, + inView: isInView, + data: widget.data[index]['data'], + ); + } else { + return Post.home( + userName: widget.userName, + inView: isInView, + data: widget.data[index]['data'], + ); + } + } + }), + ); + }), + ) + ], + ), + ); + } + + @override + void dispose() { + if (widget.data != null) { + for (var d in widget.data) { + d['type'] == 'comment'; + if (d['data'].kind == 'video') { + d['data'].videoController?.dispose(); + } + } + } + super.dispose(); + } +} diff --git a/lib/post/widgets/post_footer.dart b/lib/post/widgets/post_footer.dart index 9cf0e87b..e887b626 100644 --- a/lib/post/widgets/post_footer.dart +++ b/lib/post/widgets/post_footer.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttericon/font_awesome_icons.dart'; import 'package:fluttericon/typicons_icons.dart'; @@ -7,6 +8,9 @@ import 'package:post/post/provider/post_provider.dart'; import 'package:provider/provider.dart'; import 'package:hexcolor/hexcolor.dart'; +import '../../show_post/screens/show_post.dart'; +import '../../show_post/screens/show_post_web.dart'; + /// This Widget is responsible for the footer of the post. class PostFooter extends StatefulWidget { @@ -23,6 +27,7 @@ class PostFooter extends StatefulWidget { final String id; final PostModel data; final bool inScreen; + final String userName; const PostFooter( {super.key, required this.votes, @@ -31,7 +36,8 @@ class PostFooter extends StatefulWidget { required this.id, required this.isMyPost, required this.data, - required this.inScreen}); + required this.inScreen, + required this.userName}); @override State createState() => _PostFooterState(postVoteStatus: postVoteStatus, votes: votes); @@ -111,7 +117,7 @@ class _PostFooterState extends State { ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.surface, child: Container( - margin: EdgeInsetsDirectional.only(start: 10, end: 10), + margin: const EdgeInsetsDirectional.only(start: 10, end: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -128,7 +134,7 @@ class _PostFooterState extends State { child: Tooltip( message: 'Upvote', child: Container( - padding: EdgeInsetsDirectional.all(8), + padding: const EdgeInsetsDirectional.all(8), child: (postVoteStatus != 1) ? Icon( Typicons.up_outline, @@ -154,7 +160,7 @@ class _PostFooterState extends State { child: Tooltip( message: 'Downvote', child: Container( - padding: EdgeInsetsDirectional.all(8), + padding: const EdgeInsetsDirectional.all(8), child: (postVoteStatus != -1) ? Icon( Typicons.down_outline, @@ -170,7 +176,30 @@ class _PostFooterState extends State { ], ), InkWell( - onTap: null, + onTap: widget.inScreen + ? null + : () { + kIsWeb + ? Navigator.of(context).pushNamed( + ShowPostDetailsWeb.routeName, + arguments: { + 'data': widget.data, + 'userName': widget.userName + }) + // ? showDialog( + // context: context, + // builder: (context) => PostPopUpWeb( + // data: widget.data, + // userName: widget.userName, + // ), + // ) + : Navigator.of(context).pushNamed( + ShowPostDetails.routeName, + arguments: { + 'data': widget.data, + 'userName': widget.userName + }); + }, child: Row( children: [ Icon( diff --git a/lib/post/widgets/post_header.dart b/lib/post/widgets/post_header.dart index 371f147b..7e75dba4 100644 --- a/lib/post/widgets/post_header.dart +++ b/lib/post/widgets/post_header.dart @@ -1,10 +1,11 @@ import 'package:flutter/material.dart'; import 'package:fluttericon/font_awesome5_icons.dart'; -import 'package:post/post/widgets/post_popup_menu.dart'; +import 'package:post/post/widgets/post_pop_up_menu.dart'; import 'package:post/post/widgets/user_info_popup.dart'; import 'package:post/subreddit/screens/subreddit_screen.dart'; import '../../moderated_subreddit/screens/moderated_subreddit_screen.dart'; import '../models/post_model.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; /// This Widget is responsible for the header of the post. @@ -109,7 +110,7 @@ class _PostHeaderState extends State { size: 18, ) : const SizedBox(), - !widget.inScreen + !widget.inScreen || kIsWeb ? PostPopupMenu( isMyPost: widget.isMyPost, data: widget.data, @@ -183,12 +184,8 @@ class _PostHeaderBasicState extends State { widget.ownerType == 'User' && !widget.inProfile ? const SizedBox() : InkWell( - onTap: (!widget.inProfile) ? () { - print( - '===============================Is mod:${widget.isModerator}============================='); - showDialog( context: context, builder: (context) => UserInfoPopUp( @@ -197,17 +194,13 @@ class _PostHeaderBasicState extends State { ), ); } - : (){ - - print( - '===============================Is mod:${widget.isModerator}============================='); - - - Navigator.of(context).pushNamed( - widget.isModerator - ? ModeratedSubredditScreen.routeName - : SubredditScreen.routeName, - arguments: widget.ownerName);}, + : () { + Navigator.of(context).pushNamed( + widget.isModerator + ? ModeratedSubredditScreen.routeName + : SubredditScreen.routeName, + arguments: widget.ownerName); + }, child: Row( children: [ if (widget.inProfile) @@ -288,8 +281,6 @@ class _PostHeaderHome extends StatelessWidget { children: [ InkWell( onTap: () { - print( - '==========================On Tab==========================='); if (ownerType == 'User') { showDialog( context: context, diff --git a/lib/post/widgets/post_images_in_screen.dart b/lib/post/widgets/post_images_in_screen.dart new file mode 100644 index 00000000..ddc9b328 --- /dev/null +++ b/lib/post/widgets/post_images_in_screen.dart @@ -0,0 +1,153 @@ +import 'dart:async'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:dots_indicator/dots_indicator.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_image_slideshow/flutter_image_slideshow.dart'; +import 'package:post/post/models/post_model.dart'; +import 'package:post/post/widgets/post_tags_and_title.dart'; +import 'package:post/widgets/loading_reddit.dart'; + +class PostImagesInScreen extends StatefulWidget { + final PostModel data; + final List links; + final Size maxHeightImageSize; + final int imageNumber; + final String title; + final bool spoiler; + final bool nsfw; + final FlairId? flair; + const PostImagesInScreen({ + super.key, + required this.links, + required this.maxHeightImageSize, + required this.imageNumber, + required this.title, + required this.spoiler, + required this.nsfw, + required this.flair, + required this.data, + }); + + @override + State createState() => + _PostImagesInScreenState(imageNumber); +} + +class _PostImagesInScreenState extends State { + int imageNumber; + bool imageCounterVisible = false; + late List images; + _PostImagesInScreenState(this.imageNumber); + + void updateImageNumber(value) => setState(() { + imageNumber = value; + widget.data.imageNumber = value; + imageCounterVisible = true; + var timer; + timer = Timer(const Duration(milliseconds: 3000), () { + if (!mounted) { + timer.cancel(); + } else { + setState(() { + imageCounterVisible = false; + }); + } + }); + }); + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PostTagsAndTitle( + flair: widget.flair, + isSpoiler: widget.spoiler, + isNSFW: widget.nsfw, + title: widget.title, + ), + Container( + margin: const EdgeInsetsDirectional.only(top: 10, bottom: 10), + child: Stack( + alignment: Alignment.topRight, + children: [ + Stack( + alignment: Alignment.bottomCenter, + children: [ + ImageSlideshow( + initialPage: imageNumber, + height: !(widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width)) + .isNaN + ? (widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width) < + .5 * MediaQuery.of(context).size.height) + ? (widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width)) + : .5 * MediaQuery.of(context).size.height + : .5 * MediaQuery.of(context).size.height, + indicatorColor: Colors.white, + indicatorRadius: 0, + onPageChanged: (value) => updateImageNumber(value), + children: widget.links.map((String link) { + CachedNetworkImage image = CachedNetworkImage( + fit: BoxFit.contain, + imageUrl: link, + placeholder: (context, url) => const LoadingReddit(), + ); + return image; + }).toList(), + ), + AnimatedOpacity( + opacity: imageCounterVisible ? 1 : 0, + duration: const Duration(milliseconds: 500), + child: Container( + margin: const EdgeInsetsDirectional.only(bottom: 8), + child: DotsIndicator( + decorator: const DotsDecorator( + size: Size.square(8), + activeSize: Size.square(8), + activeColor: Colors.white, + color: Colors.transparent, + shape: CircleBorder( + side: BorderSide(width: 1, color: Colors.white), + ), + spacing: EdgeInsets.all(4.0)), + dotsCount: + widget.links.isEmpty ? 1 : widget.links.length, + position: imageNumber.toDouble(), + ), + ), + ), + ], + ), + AnimatedOpacity( + opacity: imageCounterVisible ? 1 : 0, + duration: const Duration(milliseconds: 500), + child: Container( + margin: const EdgeInsetsDirectional.only(top: 8, end: 8), + child: ClipRRect( + borderRadius: BorderRadius.circular(20.0), + child: Container( + padding: const EdgeInsetsDirectional.only( + start: 10, end: 10, top: 5, bottom: 5), + color: Colors.black.withOpacity(0.6), + child: Text( + '${(imageNumber + 1).toString()}/${widget.links.length}', + style: const TextStyle( + color: Colors.white, + overflow: TextOverflow.ellipsis), + ), + ), + ), + ), + ) + ], + ), + ), + ], + ); + } +} diff --git a/lib/post/widgets/post_images_web.dart b/lib/post/widgets/post_images_web.dart new file mode 100644 index 00000000..976b54c7 --- /dev/null +++ b/lib/post/widgets/post_images_web.dart @@ -0,0 +1,152 @@ +import 'dart:async'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:dots_indicator/dots_indicator.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_image_slideshow/flutter_image_slideshow.dart'; +import 'package:post/post/models/post_model.dart'; +import 'package:post/post/widgets/post_tags_and_title.dart'; +import 'package:post/widgets/loading_reddit.dart'; + +class PostImagesWeb extends StatefulWidget { + final PostModel data; + final List links; + final Size maxHeightImageSize; + final int imageNumber; + final String title; + final bool spoiler; + final bool nsfw; + final FlairId? flair; + const PostImagesWeb({ + super.key, + required this.links, + required this.maxHeightImageSize, + required this.imageNumber, + required this.title, + required this.spoiler, + required this.nsfw, + required this.flair, + required this.data, + }); + + @override + State createState() => _PostImagesWebState(imageNumber); +} + +class _PostImagesWebState extends State { + int imageNumber; + bool imageCounterVisible = false; + late List images; + _PostImagesWebState(this.imageNumber); + + void updateImageNumber(value) => setState(() { + imageNumber = value; + widget.data.imageNumber = value; + imageCounterVisible = true; + var timer; + timer = Timer(const Duration(milliseconds: 3000), () { + if (!mounted) { + timer.cancel(); + } else { + setState(() { + imageCounterVisible = false; + }); + } + }); + }); + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PostTagsAndTitle( + flair: widget.flair, + isSpoiler: widget.spoiler, + isNSFW: widget.nsfw, + title: widget.title, + ), + Container( + margin: const EdgeInsetsDirectional.only(top: 10, bottom: 10), + child: Stack( + alignment: Alignment.topRight, + children: [ + Stack( + alignment: Alignment.bottomCenter, + children: [ + ImageSlideshow( + initialPage: imageNumber, + height: !(widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width)) + .isNaN + ? (widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width) < + .5 * MediaQuery.of(context).size.height) + ? (widget.maxHeightImageSize.height * + (MediaQuery.of(context).size.width / + widget.maxHeightImageSize.width)) + : .5 * MediaQuery.of(context).size.height + : .5 * MediaQuery.of(context).size.height, + indicatorColor: Colors.white, + indicatorRadius: 0, + onPageChanged: (value) => updateImageNumber(value), + children: widget.links.map((String link) { + CachedNetworkImage image = CachedNetworkImage( + fit: BoxFit.cover, + imageUrl: link, + placeholder: (context, url) => const LoadingReddit(), + ); + return image; + }).toList(), + ), + AnimatedOpacity( + opacity: imageCounterVisible ? 1 : 0, + duration: const Duration(milliseconds: 500), + child: Container( + margin: const EdgeInsetsDirectional.only(bottom: 8), + child: DotsIndicator( + decorator: const DotsDecorator( + size: Size.square(8), + activeSize: Size.square(8), + activeColor: Colors.white, + color: Colors.transparent, + shape: CircleBorder( + side: BorderSide(width: 1, color: Colors.white), + ), + spacing: EdgeInsets.all(4.0)), + dotsCount: + widget.links.isEmpty ? 1 : widget.links.length, + position: imageNumber.toDouble(), + ), + ), + ), + ], + ), + AnimatedOpacity( + opacity: imageCounterVisible ? 1 : 0, + duration: const Duration(milliseconds: 500), + child: Container( + margin: const EdgeInsetsDirectional.only(top: 8, end: 8), + child: ClipRRect( + borderRadius: BorderRadius.circular(20.0), + child: Container( + padding: const EdgeInsetsDirectional.only( + start: 10, end: 10, top: 5, bottom: 5), + color: Colors.black.withOpacity(0.6), + child: Text( + '${(imageNumber + 1).toString()}/${widget.links.length}', + style: const TextStyle( + color: Colors.white, + overflow: TextOverflow.ellipsis), + ), + ), + ), + ), + ) + ], + ), + ), + ], + ); + } +} diff --git a/lib/post/widgets/post_link_in_screen.dart b/lib/post/widgets/post_link_in_screen.dart index 65817dc3..dbf4a26e 100644 --- a/lib/post/widgets/post_link_in_screen.dart +++ b/lib/post/widgets/post_link_in_screen.dart @@ -39,7 +39,7 @@ class PostLinkInScreen extends StatelessWidget { margin: const EdgeInsetsDirectional.only(top: 10, start: 10, end: 10), child: LinkPreviewGenerator( showDescription: false, - link: 'https://github.com/ghpranav/link_preview_generator', + link: link, placeholderWidget: const LoadingReddit(), backgroundColor: Colors.black.withOpacity(0.6), showTitle: false, diff --git a/lib/post/widgets/post_list.dart b/lib/post/widgets/post_list.dart index b39b87e5..b7082630 100644 --- a/lib/post/widgets/post_list.dart +++ b/lib/post/widgets/post_list.dart @@ -3,19 +3,40 @@ import 'package:inview_notifier_list/inview_notifier_list.dart'; import '../models/post_model.dart'; import './post.dart'; +/// This widget returns a CustomScrollView to display posts + class PostList extends StatefulWidget { + /// The user name final String userName; + + /// A widget to be displayed above the posts final Widget topOfTheList; + + /// A function which is invoked when the CustomScrollView reaches the end final Function updateData; + + /// The list of posts' data to be displayed final List data; + + /// The type of posts ["home", "profile", "community"] final String type; - const PostList( - {super.key, - required this.userName, - this.topOfTheList = const SizedBox(), - required this.updateData, - required this.data, - this.type = 'home'}); + + /// A margin to the left of the posts + final double leftMargin; + + /// A margin to the right of the posts + + final double rightMargin; + const PostList({ + super.key, + required this.userName, + this.topOfTheList = const SizedBox(), + required this.updateData, + required this.data, + this.type = 'home', + this.leftMargin = 0, + this.rightMargin = 0, + }); @override State createState() => _PostListState(); @@ -26,6 +47,8 @@ class _PostListState extends State { Widget build(BuildContext context) { return Flexible( child: InViewNotifierCustomScrollView( + + shrinkWrap: true, onListEndReached: () => widget.updateData(), scrollDirection: Axis.vertical, initialInViewIds: const ['0'], @@ -44,29 +67,33 @@ class _PostListState extends State { SliverList( delegate: SliverChildBuilderDelegate(childCount: widget.data.length, (context, index) { - return InViewNotifierWidget( - id: '$index', - builder: (context, isInView, child) { - if (widget.type == 'profile') { - return Post.profile( - userName: widget.userName, - inView: isInView, - data: widget.data[index], - ); - } else if (widget.type == 'community') { - return Post.community( - userName: widget.userName, - inView: isInView, - data: widget.data[index], - ); - } else { - return Post.home( - userName: widget.userName, - inView: isInView, - data: widget.data[index], - ); - } - }); + return Container( + margin: EdgeInsetsDirectional.only( + start: widget.leftMargin, end: widget.rightMargin), + child: InViewNotifierWidget( + id: '$index', + builder: (context, isInView, child) { + if (widget.type == 'profile') { + return Post.profile( + userName: widget.userName, + inView: isInView, + data: widget.data[index], + ); + } else if (widget.type == 'community') { + return Post.community( + userName: widget.userName, + inView: isInView, + data: widget.data[index], + ); + } else { + return Post.home( + userName: widget.userName, + inView: isInView, + data: widget.data[index], + ); + } + }), + ); }), ) ], @@ -85,4 +112,4 @@ class _PostListState extends State { } super.dispose(); } -} +} \ No newline at end of file diff --git a/lib/post/widgets/post_mod_popup.dart b/lib/post/widgets/post_mod_popup.dart index fca8cbef..52c3c92d 100644 --- a/lib/post/widgets/post_mod_popup.dart +++ b/lib/post/widgets/post_mod_popup.dart @@ -106,11 +106,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(start: 2, end: 5), + margin: const EdgeInsetsDirectional.only(start: 2, end: 5), child: Icon( MfgLabs.attention, size: 18, @@ -136,11 +136,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(start: 2, end: 5), + margin: const EdgeInsetsDirectional.only(start: 2, end: 5), child: Stack( alignment: Alignment.center, children: [ @@ -185,11 +185,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(end: 5), + margin: const EdgeInsetsDirectional.only(end: 5), child: Icon( Icons.lock_outline, color: Theme.of(context).colorScheme.brightness == @@ -216,11 +216,11 @@ class _PostModPopUpState extends State { InkWell( onTap: null, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(end: 5), + margin: const EdgeInsetsDirectional.only(end: 5), child: Icon( FontAwesome.mail, color: Theme.of(context).colorScheme.brightness == @@ -250,11 +250,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(end: 5), + margin: const EdgeInsetsDirectional.only(end: 5), child: Icon( Icons.block_flipped, color: widget.isRemoved @@ -288,11 +288,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(end: 5), + margin: const EdgeInsetsDirectional.only(end: 5), child: Icon( Icons.block_flipped, color: widget.data.isSpam ?? false @@ -326,11 +326,11 @@ class _PostModPopUpState extends State { Navigator.pop(context); }, child: Container( - margin: EdgeInsetsDirectional.only(bottom: 10, top: 10), + margin: const EdgeInsetsDirectional.only(bottom: 10, top: 10), child: Row( children: [ Container( - margin: EdgeInsetsDirectional.only(end: 5), + margin: const EdgeInsetsDirectional.only(end: 5), child: Icon( Icons.done, color: widget.isApproved diff --git a/lib/post/widgets/post_mod_tools.dart b/lib/post/widgets/post_mod_tools.dart index 6846bf35..f54c18d8 100644 --- a/lib/post/widgets/post_mod_tools.dart +++ b/lib/post/widgets/post_mod_tools.dart @@ -5,17 +5,40 @@ import 'package:provider/provider.dart'; import '../models/post_model.dart'; import '../provider/post_provider.dart'; +/// This widget displays the moderator tools of the post + class PostModTools extends StatefulWidget { /// Check if it's a post created by the user final bool isMyPost; + /// A boolean to determine if the post is approved + final bool isApproved; + + /// A boolean to determine if the post is NSFW + final bool isNSFW; + + /// A boolean to determine if the post is spoiler + final bool isSpoiler; + + /// A boolean to determine if the comments of the post is locked + final bool isCommentsLocked; + + /// A boolean to determine if the post is removed + final bool isRemoved; + + /// A function which is invoked when the state changes + final Function update; + + /// The post data final PostModel data; + + /// A boolean to check if in screen final bool inScreen; const PostModTools({ @@ -55,7 +78,7 @@ class _PostModTools extends State { @override Widget build(BuildContext context) { return Container( - margin: EdgeInsetsDirectional.only(top: 2), + margin: const EdgeInsetsDirectional.only(top: 2), child: Material( color: (!widget.inScreen && (widget.data.isSpam ?? false)) ? Colors.blueGrey[50] @@ -63,7 +86,7 @@ class _PostModTools extends State { ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.surface, child: Container( - margin: EdgeInsetsDirectional.only(start: 10, end: 10), + margin: const EdgeInsetsDirectional.only(start: 10, end: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -75,7 +98,7 @@ class _PostModTools extends State { child: Tooltip( message: 'Approve', child: Container( - padding: EdgeInsetsDirectional.all(10), + padding: const EdgeInsetsDirectional.all(10), child: (!widget.isApproved) ? Icon( Icons.done, @@ -108,7 +131,7 @@ class _PostModTools extends State { child: Tooltip( message: 'More options', child: Container( - padding: EdgeInsetsDirectional.all(10), + padding: const EdgeInsetsDirectional.all(10), child: Icon( Icons.format_list_bulleted, color: Theme.of(context).colorScheme.secondary, diff --git a/lib/post/widgets/post_popup_menu.dart b/lib/post/widgets/post_pop_up_menu.dart similarity index 96% rename from lib/post/widgets/post_popup_menu.dart rename to lib/post/widgets/post_pop_up_menu.dart index 2f34599c..b8434476 100644 --- a/lib/post/widgets/post_popup_menu.dart +++ b/lib/post/widgets/post_pop_up_menu.dart @@ -5,10 +5,19 @@ import 'package:provider/provider.dart'; import '../provider/post_provider.dart'; +/// This widget shows the popup menu of the widget + class PostPopupMenu extends StatefulWidget { + /// A boolean to determine if the post is saved final bool isSaved; + + /// The post data final PostModel data; + + /// A function which is invoked when the state changes final Function update; + + /// A boolean to determine if it's the user's post final bool isMyPost; const PostPopupMenu( {super.key, diff --git a/lib/post/widgets/post_pop_up_web.dart b/lib/post/widgets/post_pop_up_web.dart new file mode 100644 index 00000000..e7494ec4 --- /dev/null +++ b/lib/post/widgets/post_pop_up_web.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:responsive_sizer/responsive_sizer.dart'; + +import '../../comments/widgets/comments_list.dart'; +import '../../post/models/post_model.dart'; +import 'post.dart'; + +//import '../widgets/edit_post.dart'; + +class PostPopUpWeb extends StatefulWidget { + final String userName; + final PostModel data; + static const routeName = '/showpost-screen'; + + const PostPopUpWeb({ + super.key, + required this.userName, + required this.data, + }); + + @override + State createState() => _PostPopUpWebState(); +} + +class _PostPopUpWebState extends State { + @override + Widget build(BuildContext context) { + return AlertDialog( + content: SizedBox( + height: MediaQuery.of(context).size.width * .8, + width: MediaQuery.of(context).size.width * .8, + child: SingleChildScrollView( + child: SizedBox( + width: 40.w, + child: Column( + children: [ + Post.home( + data: widget.data, + userName: widget.userName, + inView: true, + inScreen: true), + CommentsList( + postId: widget.data.sId ?? '', + userName: widget.userName, + ) + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/post/widgets/post_tags_and_title.dart b/lib/post/widgets/post_tags_and_title.dart index 7df42298..d07b6207 100644 --- a/lib/post/widgets/post_tags_and_title.dart +++ b/lib/post/widgets/post_tags_and_title.dart @@ -4,10 +4,22 @@ import 'package:fluttericon/mfg_labs_icons.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:post/post/models/post_model.dart'; +/// This widget displays the title and the spoiler and NSFW tags + class PostTagsAndTitle extends StatefulWidget { + /// The title of the post final String title; + + /// A boolean to determine if NSFW + final bool isNSFW; + + /// A boolean to determine if spoiler + final bool isSpoiler; + + /// The flair data + final FlairId? flair; const PostTagsAndTitle( diff --git a/lib/post/widgets/post_video_in_widget.dart b/lib/post/widgets/post_video_in_widget.dart index 46915031..a7f50103 100644 --- a/lib/post/widgets/post_video_in_widget.dart +++ b/lib/post/widgets/post_video_in_widget.dart @@ -7,14 +7,29 @@ import 'package:chewie/chewie.dart'; import '../models/post_model.dart'; +/// A widget to display a video in widget class PostVideoInWidget extends StatefulWidget { /// The url of the video final String url; + + /// The video controller final VideoPlayerController videoController; + + /// A boolean to check if in view final bool inView; + + /// The title of the post final String title; + + /// A boolean to determine if spoiler final bool spoiler; + + /// A boolean to determine if NSFW + final bool nsfw; + + /// The flair data + final FlairId? flair; const PostVideoInWidget({ super.key, diff --git a/lib/post/widgets/post_video_in_widget_web.dart b/lib/post/widgets/post_video_in_widget_web.dart new file mode 100644 index 00000000..e186e5e1 --- /dev/null +++ b/lib/post/widgets/post_video_in_widget_web.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; +import 'package:post/post/widgets/post_tags_and_title.dart'; +import 'package:post/providers/global_settings.dart'; +import 'package:post/widgets/loading_reddit.dart'; +import 'package:provider/provider.dart'; +import 'package:video_player/video_player.dart'; +import 'package:chewie/chewie.dart'; + +import '../models/post_model.dart'; + +/// A widget to display a video in widget (web) + +class PostVideoInWidgetWeb extends StatefulWidget { + /// The url of the video + final String url; + + /// The video controller + + final VideoPlayerController videoController; + + /// A boolean to check if in view + + final bool inView; + + /// The title of the post + + final String title; + + /// A boolean to determine if spoiler + + final bool spoiler; + + /// A boolean to determine if NSFW + + final bool nsfw; + + /// The flair data + + final FlairId? flair; + const PostVideoInWidgetWeb({ + super.key, + required this.url, + required this.videoController, + required this.inView, + required this.title, + required this.spoiler, + required this.nsfw, + required this.flair, + }); + + @override + State createState() => _PostVideoInWidgetWebState(); +} + +class _PostVideoInWidgetWebState extends State { + late ChewieController chewieController; + bool isMuted = true; + bool autoPlay = true; + @override + void initState() { + super.initState(); + chewieController = ChewieController( + videoPlayerController: widget.videoController, + autoInitialize: true, + autoPlay: false, + looping: true, + showControls: true, + allowMuting: false, + allowPlaybackSpeedChanging: true, + placeholder: const LoadingReddit(), + ); + } + + updateMuted() { + if (Provider.of(context, listen: false).getIsMuted) { + widget.videoController.setVolume(0); + } else { + widget.videoController.setVolume(1); + } + setState(() { + isMuted = Provider.of(context, listen: false).getIsMuted; + }); + } + + play() { + if (Provider.of(context, listen: false).getIsMuted) { + widget.videoController.setVolume(0); + } else { + widget.videoController.setVolume(1); + } + widget.videoController.play(); + setState(() { + isMuted = Provider.of(context, listen: false).getIsMuted; + }); + } + + toggleSound() { + if (Provider.of(context, listen: false).getIsMuted) { + Provider.of(context, listen: false).unMute(); + updateMuted(); + } else { + Provider.of(context, listen: false).mute(); + updateMuted(); + } + } + + @override + Widget build(BuildContext context) { + if (widget.inView && !widget.videoController.value.isPlaying && autoPlay) { + { + play(); + } + } else if (!widget.inView && widget.videoController.value.isPlaying) { + { + widget.videoController.pause(); + widget.videoController.seekTo(const Duration(seconds: 0)); + updateMuted(); + } + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PostTagsAndTitle( + flair: widget.flair, + isSpoiler: widget.spoiler, + isNSFW: widget.nsfw, + title: widget.title, + ), + Center( + child: widget.videoController.value.isInitialized + ? Container( + margin: const EdgeInsetsDirectional.only( + start: 20, end: 20, top: 10), + height: (widget.videoController.value.size.height * + (MediaQuery.of(context).size.width / + widget.videoController.value.size.width) < + MediaQuery.of(context).size.height * .5) + ? widget.videoController.value.size.height * + (MediaQuery.of(context).size.width / + widget.videoController.value.size.width) + : MediaQuery.of(context).size.height * 0.5, + child: Stack( + alignment: Alignment.center, + children: [ + Stack( + alignment: Alignment.bottomRight, + children: [ + Align( + alignment: Alignment.center, + child: AspectRatio( + aspectRatio: + widget.videoController.value.aspectRatio, + child: Chewie( + controller: chewieController, + ), + ), + ), + GestureDetector( + onTap: () => toggleSound(), + child: Container( + margin: const EdgeInsetsDirectional.all(10), + child: ClipRRect( + borderRadius: BorderRadius.circular(20.0), + child: Container( + padding: const EdgeInsetsDirectional.all(2), + color: Colors.black.withOpacity(0.5), + child: Icon( + isMuted + ? Icons.volume_off + : Icons.volume_up, + color: Colors.white, + size: 15, + ), + ), + ), + ), + ), + ], + ), + !autoPlay + ? GestureDetector( + onTap: () { + autoPlay = true; + play(); + }, + child: Container( + margin: const EdgeInsetsDirectional.all(10), + child: const Icon( + Icons.play_circle_outline_rounded, + color: Colors.white, + size: 50, + ), + ), + ) + : const SizedBox(), + ], + ), + ) + : Container(), + ), + ], + ); + } + + @override + void dispose() { + chewieController.dispose(); + super.dispose(); + } +} diff --git a/lib/post/widgets/user_info_popup.dart b/lib/post/widgets/user_info_popup.dart index 05603e72..f008d2c4 100644 --- a/lib/post/widgets/user_info_popup.dart +++ b/lib/post/widgets/user_info_popup.dart @@ -10,8 +10,12 @@ import '../../other_profile/models/others_profile_data.dart'; import '../../other_profile/providers/other_profile_provider.dart'; import '../../widgets/loading_reddit.dart'; +/// A pop up (AlertDialog) to show the user info class UserInfoPopUp extends StatefulWidget { + /// the name of the user to get his data final String authorName; + + /// A boolean to determine the look of the pop up final bool isMine; const UserInfoPopUp({ super.key, @@ -181,7 +185,6 @@ class _UserInfoPopUpState extends State { !widget.isMine ? InkWell( onTap: () { - _showLeaveDialog(); }, child: Container( @@ -282,7 +285,7 @@ class _UserInfoPopUpState extends State { context: context, builder: (ctx) => AlertDialog( //title:Text('Are you sure you want to leave the r/${widget.communityName.toString()} community?'), - content: Container( + content: SizedBox( //color: Colors.amber, height: 12.h, width: 100.w, @@ -304,7 +307,7 @@ class _UserInfoPopUpState extends State { ), ), actions: [ - Container( + SizedBox( width: 35.w, height: 6.h, child: ElevatedButton( @@ -321,7 +324,7 @@ class _UserInfoPopUpState extends State { }, ), ), - Container( + SizedBox( width: 35.w, height: 6.h, child: ElevatedButton( diff --git a/lib/providers/Profile_provider.dart b/lib/providers/profile_provider.dart similarity index 100% rename from lib/providers/Profile_provider.dart rename to lib/providers/profile_provider.dart diff --git a/lib/show_post/screens/show_post_web.dart b/lib/show_post/screens/show_post_web.dart new file mode 100644 index 00000000..099e0348 --- /dev/null +++ b/lib/show_post/screens/show_post_web.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:post/comments/screens/add_comment_screen.dart'; +import 'package:responsive_sizer/responsive_sizer.dart'; + +import '../../comments/widgets/comments_list.dart'; +import '../../notification/widgets/list_tile_widget.dart'; +import '../../post/models/post_model.dart'; +import '../../post/widgets/post.dart'; +import '../widgets/edit_post.dart'; + +class ShowPostDetailsWeb extends StatefulWidget { + static const routeName = '/showpost-screen'; + + const ShowPostDetailsWeb({ + super.key, + }); + + @override + State createState() => _ShowPostDetailsWebState(); +} + +class _ShowPostDetailsWebState extends State { + late String userName; + late PostModel data; + @override + void didChangeDependencies() { + // TODO: implement didChangeDependencies + //===============================Fetch subreddit data =======================================// + + var temp = + ModalRoute.of(context)?.settings.arguments as Map; + userName = temp['userName']; + data = temp['data']; + super.didChangeDependencies(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.blue, + actions: [ + // IconButton( + // onPressed: () { + PopupMenuButton( + // elevation: -1, + // position: PopupMenuPosition.under, + constraints: BoxConstraints.expand(width: 60.w, height: 55.h), + icon: const Icon(Icons.more_vert, color: Colors.white), + itemBuilder: (context) { + //return list.map((e) { + return [ + PopupMenuItem( + child: ListTileWidget(icon: Icons.share, title: 'Share')), + PopupMenuItem( + child: ListTileWidget(icon: Icons.save, title: 'Save')), + PopupMenuItem( + child: + ListTileWidget(icon: Icons.copy, title: 'Copy text')), + PopupMenuItem( + child: ListTileWidget( + icon: Icons.edit, + title: 'Edit', + onpressed: () => Navigator.of(context) + .popAndPushNamed(EditPost.routeName))), + PopupMenuItem( + child: ListTileWidget( + icon: Icons.tag, title: 'Add post flair')), + PopupMenuItem( + child: ListTileWidget( + icon: Icons.warning, title: 'Mark spoiler')), + PopupMenuItem( + child: ListTileWidget( + icon: Icons.plus_one, title: 'Mark NSFW')), + PopupMenuItem( + child: ListTileWidget(icon: Icons.delete, title: 'Delete')), + ]; + }, + ), + ], + ), + body: Center( + child: Container( + width: 50.w, + child: SingleChildScrollView( + child: Column( + children: [ + Post.home( + data: data, + userName: userName, + inView: true, + inScreen: true), + CommentsList( + postId: data.sId ?? '', + userName: userName, + ) + ], + ), + ), + ), + ), + bottomNavigationBar: Padding( + padding: const EdgeInsetsDirectional.all(5), + child: GestureDetector( + onTap: () { + Get.to(AddCommentScreen(), + arguments: {'parentId': data.sId, 'title': data.title}); + }, + child: Container( + decoration: BoxDecoration( + color: Colors.grey[100], + border: Border.all( + color: Colors.grey, + ), + ), + child: const Padding( + padding: EdgeInsetsDirectional.all(5), + child: Text( + 'Add a comment', + style: TextStyle(color: Colors.grey), + ), + ), + ), + ) + + // TextFormField( + // onChanged: (value) {}, + // onTap: () { + // Get.to(AddCommentScreen(), + // arguments: {'parentId': data.sId, 'title': data.title}); + // }, + // enabled: false, + // style: const TextStyle(fontSize: 14.0, fontWeight: FontWeight.w700), + // showCursor: true, + + // textAlign: TextAlign.start, + // decoration: InputDecoration( + // hintText: 'Add a comment', + // enabledBorder: OutlineInputBorder( + // borderSide: + // BorderSide(width: 2, color: Colors.grey), //<-- SEE HERE + // borderRadius: BorderRadius.circular(10.0), + // ), + // ), + // ), + ), + ); + } +} diff --git a/lib/subreddit/models/subreddit_data.dart b/lib/subreddit/models/subreddit_data.dart index a63bb27d..5925d81d 100644 --- a/lib/subreddit/models/subreddit_data.dart +++ b/lib/subreddit/models/subreddit_data.dart @@ -28,25 +28,6 @@ class SubredditData { required this.rules, required this.moderators}); SubredditData.fromJson(Map json) { - // id = json['_id']; - // name = json['fixedName']; - // displayName = json['name']; - // subredditPicture = json['icon']; - // subredditBackPicture = json['backgroundImage']; - // description = json['description']; - // subredditLink = json['subredditLink']; - // numOfMembers = int.parse(json['membersCount'].toString()); - // numOfOnlines = int.parse(json['numOfOnlines'].toString()); - // isJoined = (json['isJoined']); - // final List loadedrule = []; - // json['rules'].forEach((rule) { - // loadedrule.add(SubredditAboutRules(rule['title'], rule['description'])); - // }); - // rules = loadedrule; - // final List loadedmodrator = []; - // json['moderators'].forEach((moderator) { - // loadedmodrator.add(moderator["userName"]); - print(json); id = json['_id']; name = json['fixedName']; displayName = json['name']; @@ -54,7 +35,7 @@ class SubredditData { subredditBackPicture = json['backgroundImage']; description = json['description']; subredditLink = json['subredditLink']; - numOfMembers = 0; //int.parse(json['membersCount'].toString()); + numOfMembers = int.parse(json['membersCount'].toString()); numOfOnlines = 0; //int.parse(json['numOfOnlines'].toString()); isJoined = (json['isJoined']); final List loadedrule = []; @@ -69,57 +50,4 @@ class SubredditData { moderators = loadedmodrator; } -// { -// "id": 10, -// "name": "Cooking", -// "displayName": "Cooking Good", -// "subredditPicture": "https://previews.123rf.com/images/seamartini/seamartini1609/seamartini160900764/64950290-chef-toque-vector-sketch-icon-cook-cap-kitchen-cooking-hat-emblem-for-restaurant-design-element-bake.jpg", -// "subredditBackPicture": "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fassets.marthastewart.com%2Fstyles%2Fwmax-750%2Fd30%2Feasy-basic-pancakes-horiz-1022%2Feasy-basic-pancakes-horiz-1022_0.jpg%3Fitok%3DXQMZkp_j", -// "description": "Iam Chef", -// "subredditLink": "https://previews.123rf.com/images/seamartini/seamartini1609/seamartini160900764/64950290-chef-toque-vector-sketch-icon-cook-cap-kitchen-cooking-hat-emblem-for-restaurant-design-element-bake.jpg", -// "numOfMembers": 10398, -// "numOfOnlines": 1789, -// "rules": [{ -// "title": "no codeing", -// "description": "i hate coding" -// }, -// { -// "title": "no codeing", -// "description": "i hate coding" -// }, -// { -// "title": "no codeing", -// "description": "i hate coding" -// } -// ], -// "moderators": [{ -// "userName": "Ali" -// }, -// { -// "userName": "omer" -// }, -// { -// "userName": "zeinab" -// }, -// { -// "userName": "mazen" -// } -// ], -// "isJoined": true -// } - // Map toJson() { - // final Map data = new Map(); - // data['id'] = this.id; - // data['name'] = this.name; - // data['subredditPicture'] = this.subredditPicture; - // data['subredditBackPicture'] = this.subredditBackPicture; - // data['subredditLink'] = this.subredditLink; - // data['description'] = this.description; - // data['numOfMembers'] = this.numOfMembers; - // data['numOfOnlines'] = this.numOfOnlines; - // data['isJoined'] = this.isJoined; - // data['rules'] = this.rules; - // // data['moderators'] = this.moderators; - // return data; - // } } diff --git a/lib/subreddit/providers/subreddit_provider.dart b/lib/subreddit/providers/subreddit_provider.dart index 3e40434d..7bd7bc13 100644 --- a/lib/subreddit/providers/subreddit_provider.dart +++ b/lib/subreddit/providers/subreddit_provider.dart @@ -17,7 +17,9 @@ class SubredditProvider with ChangeNotifier { bool? get gettingTheme { return showTheme; } - + // ===================================this function used to===========================================// +//==================fetch and set date===========================// +//moderatedSubredditUserName==> userName Of Subreddit Future fetchAndSetSubredddit( String subredditUserName, BuildContext context) async { try { @@ -26,8 +28,6 @@ class SubredditProvider with ChangeNotifier { DioClient.init(prefs); await DioClient.get(path: '/subreddits/${subredditUserName}') .then((response) { - print('lllllllllllllllllllllllllllllllllllll'); - print(response.data['data']); loadSubreddit = SubredditData.fromJson(response.data['data']); notifyListeners(); }); @@ -37,7 +37,10 @@ class SubredditProvider with ChangeNotifier { HandleError.handleError(error.toString(), context); } } - + // ===================================this function used to===========================================// +//==================Join and Disjoin subbreddit ===========================// +//moderatedSubredditUserName==> userName Of Subreddit +//action==> action either sub or unsub Future joinAndDisjoinSubreddit( String subredditUserName, String action, BuildContext context) async { try { diff --git a/lib/subreddit/screens/subreddit_screen.dart b/lib/subreddit/screens/subreddit_screen.dart index 43e98eb9..91ce6bb4 100644 --- a/lib/subreddit/screens/subreddit_screen.dart +++ b/lib/subreddit/screens/subreddit_screen.dart @@ -3,6 +3,7 @@ import 'package:get/get.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:provider/provider.dart'; +import 'package:get/get.dart'; import '../../home/controller/home_controller.dart'; import '../../models/subreddit_data.dart'; import '../../widgets/loading_reddit.dart'; @@ -10,6 +11,10 @@ import '../widgets/subreddit_web.dart'; import '../widgets/subreddit_app.dart'; import '../providers/subreddit_provider.dart'; import '../../home/widgets/end_drawer.dart'; +import '../../home/controller/home_controller.dart'; +import '../../createpost/controllers/posts_controllers.dart'; +import '../../home/widgets/custom_upper_bar.dart'; + class SubredditScreen extends StatefulWidget { static const routeName = '/Subreddit'; @@ -35,7 +40,7 @@ class _SubredditScreenState extends State isScrollable: true, tabs: tabs, labelColor: Colors.black, - labelPadding:EdgeInsets.symmetric(horizontal: 18.w), + labelPadding: EdgeInsets.symmetric(horizontal: 18.w), labelStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), indicatorColor: Colors.blue, ); @@ -43,7 +48,7 @@ class _SubredditScreenState extends State var _isLoading = false; var _isInit = true; var subredditUserName; -SubredditData? loadedSubreddit; + SubredditData? loadedSubreddit; //===============================================================================// @override void initState() { @@ -57,17 +62,18 @@ SubredditData? loadedSubreddit; super.dispose(); } + // ===================================this function used to===========================================// +//==================fetch date for first time===========================// @override void didChangeDependencies() { // TODO: implement didChangeDependencies - //===============================doing fetch=======================================// if (_isInit) { setState(() { _isLoading = true; }); subredditUserName = ModalRoute.of(context)?.settings.arguments as String; Provider.of(context, listen: false) - .fetchAndSetSubredddit(subredditUserName,context) + .fetchAndSetSubredddit(subredditUserName, context) .then((value) { loadedSubreddit = Provider.of(context, listen: false) .gettingSubredditeData; @@ -77,16 +83,28 @@ SubredditData? loadedSubreddit; }); } _isInit = false; - - //==================================================// super.didChangeDependencies(); } + final HomeController controllerHome = Get.put( + HomeController(), + ); + final PostController controllerForPost = Get.put( + PostController(), + ); @override Widget build(BuildContext context) { final GlobalKey _scaffoldKey = GlobalKey(); return Scaffold( key: _scaffoldKey, + appBar: (kIsWeb) + ? PreferredSize( + preferredSize: Size(700, 60), + child: UpBar( + controller: controllerHome, + controllerForCreatePost: controllerForPost, + )) + : null, body: _isLoading ? LoadingReddit() : kIsWeb @@ -103,7 +121,10 @@ SubredditData? loadedSubreddit; tabBar: _tabBar, loadedSubreddit: loadedSubreddit as SubredditData, userName: subredditUserName), - endDrawer: _isLoading ? LoadingReddit() : endDrawer(controller: controller,)); + endDrawer: _isLoading + ? LoadingReddit() + : endDrawer( + controller: controller, + )); } - - } +} diff --git a/lib/subreddit/widgets/notify_button_web.dart b/lib/subreddit/widgets/notify_button_web.dart index f57180a5..3462eab2 100644 --- a/lib/subreddit/widgets/notify_button_web.dart +++ b/lib/subreddit/widgets/notify_button_web.dart @@ -42,12 +42,11 @@ class _NotifyButtonWebState extends State { PopupMenuItem( value: "Off", child: Row( - children: [ + children: const [ Icon( Icons.notifications_off, ), SizedBox( - // sized box with width 10 width: 4, ), Text("Off") @@ -57,10 +56,9 @@ class _NotifyButtonWebState extends State { PopupMenuItem( value: "Low", child: Row( - children: [ + children: const [ Icon(Icons.notifications), SizedBox( - // sized box with width 10 width: 4, ), Text("Low") @@ -70,10 +68,9 @@ class _NotifyButtonWebState extends State { PopupMenuItem( value: 'Frequent', child: Row( - children: [ + children: const [ Icon(Icons.notifications_active), SizedBox( - // sized box with width 10 width: 4, ), Text('Frequent') diff --git a/lib/subreddit/widgets/subreddit_card_information_web.dart b/lib/subreddit/widgets/subreddit_card_information_web.dart index fded8f46..327260c6 100644 --- a/lib/subreddit/widgets/subreddit_card_information_web.dart +++ b/lib/subreddit/widgets/subreddit_card_information_web.dart @@ -24,7 +24,7 @@ class _SubredditCardInformationWebState Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(right: 180, top: 100), - width: 60.w, + width: 50.w, height: 40.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white), @@ -36,15 +36,15 @@ class _SubredditCardInformationWebState width: 100.h, height: 6.h, padding: const EdgeInsets.only(top: 20, left: 10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5), + color: Colors.blue, + ), child: const Text( 'About Community', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5), - color: Colors.blue, - ), ), Container( width: 100.h, @@ -173,7 +173,6 @@ class _SubredditCardInformationWebState value: chooseTheme, onChanged: (value) { setState(() => chooseTheme = value); - print('==========================in theme============================='); Provider.of(context, listen: true) .togglingTheme(); }, diff --git a/lib/subreddit/widgets/subreddit_join_buttons.dart b/lib/subreddit/widgets/subreddit_join_buttons.dart index 72391b88..c1c3e34c 100644 --- a/lib/subreddit/widgets/subreddit_join_buttons.dart +++ b/lib/subreddit/widgets/subreddit_join_buttons.dart @@ -3,6 +3,7 @@ import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; import '../providers/subreddit_provider.dart'; import '../../widgets/custom_snack_bar.dart'; + class JoinButtons extends StatefulWidget { bool isJoined; String communityuserName; @@ -83,28 +84,29 @@ class JoinButtonsState extends State { )); } + // ===================================the next two function used to===========================================// +//==================to join subreddit===========================// +//communityName==> commuintyUserName you want to join Future subscribe(BuildContext context) async { - print('===============================Subcribe=================================='); bool sub = await Provider.of(context, listen: false) .joinAndDisjoinSubreddit(widget.communityuserName, 'sub', context); if (sub) { - join(); - ScaffoldMessenger.of(context).showSnackBar( + setState(() { + join(); + }); + ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar( isError: false, text: 'Join Successfully', disableStatus: true), ); - } - else{ - ScaffoldMessenger.of(context).showSnackBar( + } else { + ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar(isError: true, text: 'Join Failed', disableStatus: true), - );} + ); + } } bool join() { - setState(() { - isJoinedstate = true; - }); - + isJoinedstate = true; return isJoinedstate; } @@ -186,7 +188,10 @@ class JoinButtonsState extends State { return tappedIndex; } - //to Disjoin from subreddit + // ===================================the next three function used to===========================================// +//==================to disjoin of subreddit===========================// +// have two option one:leave subreddit two: cancel +//communityName==> commuintyUserName you want to leave void _showLeaveDialog() { showDialog( context: context, @@ -225,7 +230,7 @@ class JoinButtonsState extends State { ), child: const Text('Leave'), onPressed: () async { - await unSubescribe( ctx); + await unSubescribe(ctx); }, ), ) @@ -235,28 +240,24 @@ class JoinButtonsState extends State { } Future unSubescribe(BuildContext ctx) async { - print('===============================Un Subcribe=================================='); bool unSub = await Provider.of(context, listen: false) .joinAndDisjoinSubreddit(widget.communityuserName, 'unsub', context); if (unSub) { - disJoin(); - ScaffoldMessenger.of(context).showSnackBar( + setState(() { + disJoin(); + }); + ScaffoldMessenger.of(context).showSnackBar( CustomSnackBar( isError: false, text: 'Leave Successfully', disableStatus: true), ); - } - else{ - ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar( + } else { + ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar( isError: true, text: 'Leave Failed', disableStatus: true)); } Navigator.of(ctx).pop(); } - bool disJoin() { - setState(() { - isJoinedstate = false; - }); - + isJoinedstate = false; return isJoinedstate; } } diff --git a/lib/subreddit/widgets/subreddit_pop_up_menu_button.dart b/lib/subreddit/widgets/subreddit_pop_up_menu_button.dart index 7bd8127e..4a5adbde 100644 --- a/lib/subreddit/widgets/subreddit_pop_up_menu_button.dart +++ b/lib/subreddit/widgets/subreddit_pop_up_menu_button.dart @@ -19,7 +19,6 @@ class _SubredditPopupMenuButtonState extends State { return PopupMenuButton( onSelected: (value) { if (value.toString() == '/communitymodmessage' - // ||value.toString() == '/communityinfo' ) { Navigator.pushNamed(context, value.toString()); } else if (value.toString() == 'Share') { @@ -47,7 +46,7 @@ class _SubredditPopupMenuButtonState extends State { ); } // to copy Link of Subreddit -//byu using copy clipboard +//by using copy clipboard Future shareCommunitySheetButton(BuildContext context) { return showModalBottomSheet( backgroundColor: Colors.transparent, diff --git a/lib/subreddit/widgets/subreddit_post_web.dart b/lib/subreddit/widgets/subreddit_post_web.dart index afd7ae6a..52cf339a 100644 --- a/lib/subreddit/widgets/subreddit_post_web.dart +++ b/lib/subreddit/widgets/subreddit_post_web.dart @@ -1,9 +1,15 @@ import 'package:flutter/material.dart'; //import 'package:flutter_code_style/analysis_options.yaml'; import 'package:responsive_sizer/responsive_sizer.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../../widgets/sort_bottom_web.dart'; import '../../models/subreddit_data.dart'; import '../widgets/subreddit_card_information_web.dart'; +import '../../widgets/loading_reddit.dart'; +import '../../post/models/post_model.dart'; +import '../../post/widgets/post_list.dart'; +import 'package:provider/provider.dart'; +import '../../providers/subreddit_posts_provider.dart'; class SubredditePostWeb extends StatefulWidget { final SubredditData? loadedSubreddit; @@ -11,72 +17,112 @@ class SubredditePostWeb extends StatefulWidget { Key? key, required this.loadedSubreddit, }) : super(key: key); - - // Posts(this.routeNamePop); @override State createState() => _SubredditePostWebState(); } class _SubredditePostWebState extends State { + int _page = 1; + List? posts = []; + bool _isLoadMoreRunning = false; + String? userName; + bool _isInit = true; + bool _isLoading = false; + late ScrollController _scrollController; + //=====================================this function is used to======================================// + //=================Loading More Data====================// + void _loadMore() { + if (_isLoading == false && _isLoadMoreRunning == false) { + setState(() { + toggleLoadingMore(); // Display a progress indicator at the bottom + }); + setState(() { + _page += 1; + }); + // Increase _page by + + setState(() { + toggleLoadingMore(); + }); + } + } + //=====================================this function is used to======================================// + //=================Start loading More Data====================// + bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; +//=====================================this function is used to======================================// + //=================Loading Data for first time====================// + @override + Future didChangeDependencies() async { + // TODO: implement didChangeDependencies + if (_isInit) { + setState(() { + _isLoading = true; + }); + //New Hot Top + await Provider.of(context, listen: false) + .fetchSubredditePosts(widget.loadedSubreddit!.name.toString(), 'hot', + _page, 25, context) + .then((value) async { + posts = + await Provider.of(context, listen: false) + .gettingSubredditPostData; + }); + final prefs = await SharedPreferences.getInstance(); + userName = prefs.getString('userName'); + setState(() { + _isLoading = false; + }); + } + _isInit = false; + super.didChangeDependencies(); + } + @override Widget build(BuildContext context) { - return ListView( - scrollDirection: Axis.vertical, - children: [ - Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - flex: 2, - child: Column( - children: [ - SizedBox( - height: 10.h, - ), - Container( - height: 6.h, - width: 50.w, - margin: EdgeInsets.only(left: 100, top: 40), - child: SortBottomWeb(page: 1,userName:widget.loadedSubreddit!.name.toString()), - color: Colors.white, - // width: 100.w, - ), - Container( - margin: EdgeInsets.only(left: 100, bottom: 90, top: 30), - height: 30.h, - width: 50.w, - // color: Colors.white, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: const [ - Expanded( - child: ListTile( - title: Text('Post'), - ), - ), - ], - ), - ) - ]), + return (_isLoading || _isLoadMoreRunning) + ? LoadingReddit() + : (posts != null) + ? PostList( + leftMargin: 15.w, + rightMargin: 35.w, + topOfTheList: Container( + height: 65.h, + width: 50.h, + margin: EdgeInsets.only(left: 15.w), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SubredditCardInformationWeb( + loadedSubreddit: widget.loadedSubreddit), + SortBottomWeb( + page: 1, + userName: widget.loadedSubreddit!.name.toString()), + ], ), - ], - ), - ), - Expanded( - child: SubredditCardInformationWeb( - loadedSubreddit: widget.loadedSubreddit, - )), - ], - ), - ], - ); + ), + userName: userName.toString(), + updateData: _loadMore, + data: posts as List, + type: 'community', + ) + + : Center( + child: Column( + children: [ + SizedBox( + height: 30.h, + ), + const Icon( + Icons.reddit, + size: 100, + ), + const Text( + 'Wow,such empty', + style: TextStyle(color: Colors.grey), + ) + ], + ), + ); } } diff --git a/lib/subreddit/widgets/subreddit_posts.dart b/lib/subreddit/widgets/subreddit_posts.dart deleted file mode 100644 index fe85a06b..00000000 --- a/lib/subreddit/widgets/subreddit_posts.dart +++ /dev/null @@ -1,87 +0,0 @@ -// import 'package:flutter/material.dart'; -// import 'package:post/widgets/loading_reddit.dart'; -// import 'package:provider/provider.dart'; -// //import 'package:flutter_code_style/analysis_options.yaml'; -// import 'package:responsive_sizer/responsive_sizer.dart'; -// import '../../post/models/post_model.dart'; -// import '../../providers/subreddit_post.dart'; -// import '../../widgets/post_sort_bottom.dart'; -// import '../../post/widgets/post.dart'; -// import '../../post/test_data.dart'; - -// class SubredditPosts extends StatefulWidget { -// final String routeNamePop; -// final String subredditName; -// SubredditPosts({ -// Key? key, -// required this.routeNamePop, -// required this.subredditName, -// }) : super(key: key); -// // [ -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'}, -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'}, -// // {'username': 'ahmed', 'title': 'hello world1'}, -// // {'username': 'sayed', 'title': 'hello world2'}, -// // {'username': 'sayed', 'title': 'hello world3'} -// // ]; -// // Posts(this.routeNamePop); -// @override -// State createState() => _SubredditPosts(); -// } - -// class _SubredditPosts extends State { -// // final String routeNamePop; -// // _PostsState(this.routeNamePop); -// bool _isInit = true; -// bool _isLoading = false; -// List? posts = []; -// @override -// void didChangeDependencies() { -// if (_isInit) { -// setState(() { -// _isLoading = true; -// }); -// Provider.of(context, listen: false) -// .fetchNewProfilePosts(widget.subredditName) -// .then((value) { -// posts = Provider.of(context, listen: false) -// .gettingProfilePostData; -// setState(() { -// _isLoading = false; -// }); -// }); -// } -// _isInit = false; -// super.didChangeDependencies(); -// } - -// @override -// Widget build(BuildContext context) { -// return _isLoading -// ? LoadingReddit() -// : ListView( -// scrollDirection: Axis.vertical, -// children: [ -// PostSortBottom( -// widget.routeNamePop, -// //_dropDownValue, _icon -// ), -// //Select the type of Posts -// SingleChildScrollView( -// child: ListView.builder( -// physics: const ClampingScrollPhysics(), -// shrinkWrap: true, -// itemBuilder: ((context, index) => Post.community( -// data: posts![index], -// )), -// itemCount: posts?.length, -// ), -// ), -// ], -// ); -// } -// } diff --git a/lib/subreddit/widgets/subreddit_web.dart b/lib/subreddit/widgets/subreddit_web.dart index 126ac63e..f54b5d46 100644 --- a/lib/subreddit/widgets/subreddit_web.dart +++ b/lib/subreddit/widgets/subreddit_web.dart @@ -8,6 +8,9 @@ import '../providers/subreddit_provider.dart'; import 'package:provider/provider.dart'; import '../widgets/subreddit_post_web.dart'; import '../../widgets/subreddit_join_button_web.dart'; +import '../../widgets/back_to_button.dart'; +import '../screens/subreddit_screen.dart'; + extension ColorExtension on String { toColor() { var hexString = this; @@ -17,6 +20,7 @@ extension ColorExtension on String { return Color(int.parse(buffer.toString(), radix: 16)); } } + class SubredditWeb extends StatelessWidget { String userName; SubredditWeb( @@ -34,16 +38,35 @@ class SubredditWeb extends StatelessWidget { final TabBar tabBar; bool isLoading; TabController? controller; - + ScrollController scrollController = ScrollController(); @override Widget build(BuildContext context) { - bool showTheme= Provider.of(context, listen: true).gettingTheme as bool; + bool showTheme = Provider.of(context, listen: false) + .gettingTheme as bool; final GlobalKey _scaffoldKey = GlobalKey(); return Scaffold( key: _scaffoldKey, + floatingActionButtonLocation: FloatingActionButtonLocation.miniEndFloat, + floatingActionButton: Padding( + padding: const EdgeInsetsDirectional.only(end: 320.0), + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pushNamed(SubredditScreen.routeName, + arguments:userName); + }, + child: Text( + ' Back to top ', + style: TextStyle(color: Colors.white), + ), + style: ElevatedButton.styleFrom( + shape: StadiumBorder(), backgroundColor: Colors.blue), + ), + ), backgroundColor: (showTheme) ? Color.fromARGB(255, 218, 224, 230) - : (loadedSubreddit!.theme!.contains('https'))?Image.network(loadedSubreddit!.theme.toString()).color:'#6ae792'.toColor(), + : (loadedSubreddit!.theme!.contains('https')) + ? Image.network(loadedSubreddit!.theme.toString()).color + : '#6ae792'.toColor(), body: isLoading ? const Center( child: Icon( @@ -96,7 +119,6 @@ class SubredditWeb extends StatelessWidget { left: 0, bottom: 0, child: Container( - // padding: EdgeInsets.only(left: 250), color: Colors.white, child: Column( mainAxisAlignment: @@ -105,7 +127,6 @@ class SubredditWeb extends StatelessWidget { CrossAxisAlignment.start, children: [ Container( - //margin: EdgeInsets.only(top: 15), width: 100.w, height: 15.h, padding: EdgeInsets.only(left: 250), @@ -118,8 +139,6 @@ class SubredditWeb extends StatelessWidget { Container( width: 10.w, height: 20.h, - // margin: EdgeInsets.only(bottom: 30,top: 40), - decoration: BoxDecoration( color: Colors.orange, shape: BoxShape.circle, @@ -155,8 +174,6 @@ class SubredditWeb extends StatelessWidget { SubredditJoinButtonWeb( isJoined: loadedSubreddit! .isJoined as bool, - // icon: icon, - //dropDownValue: dropDownValue, communityName: loadedSubreddit!.name .toString()), @@ -180,7 +197,6 @@ class SubredditWeb extends StatelessWidget { SubredditePostWeb( loadedSubreddit: loadedSubreddit, ), - // SubredditPosts(routeNamePop: SubredditScreen.routeName), SubredditAbout( rules: loadedSubreddit!.rules as List, diff --git a/lib/widgets/back_to_button.dart b/lib/widgets/back_to_button.dart index 3a4f35ef..49007c91 100644 --- a/lib/widgets/back_to_button.dart +++ b/lib/widgets/back_to_button.dart @@ -61,7 +61,7 @@ class _BackToTopButtonState extends State { shape: StadiumBorder(), ), margin: EdgeInsets.only(right: width * 0.20), - child: Text( + child: const Text( 'Back to Top', style:TextStyle(color: Colors.white), ), diff --git a/lib/widgets/myprofile_comment_web.dart b/lib/widgets/myprofile_comment_web.dart index 4655d27d..d7a7b936 100644 --- a/lib/widgets/myprofile_comment_web.dart +++ b/lib/widgets/myprofile_comment_web.dart @@ -3,7 +3,7 @@ import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; import 'package:fluttericon/typicons_icons.dart'; import '../models/comments_data.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import '../widgets/loading_reddit.dart'; class MyProfileCommentWeb extends StatefulWidget { @@ -47,6 +47,8 @@ class _MyProfileCommentWebState extends State { } ScrollController _scrollController = new ScrollController(); + //=====================================this function is used to======================================// + //=================Loading More Data====================// void loadMore() async { if (_isLoading == false && _isLoadMoreRunning == false && @@ -75,7 +77,8 @@ class _MyProfileCommentWebState extends State { }); } } - +//=====================================this function is used to======================================// + //=================Start loading More Data====================// bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; @override @@ -84,7 +87,8 @@ class _MyProfileCommentWebState extends State { super.initState(); _scrollController = ScrollController()..addListener(loadMore); } - + //=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override Future didChangeDependencies() async { // TODO: implement didChangeDependencies diff --git a/lib/widgets/myprofile_post_web.dart b/lib/widgets/myprofile_post_web.dart index fa0b0a8b..81984007 100644 --- a/lib/widgets/myprofile_post_web.dart +++ b/lib/widgets/myprofile_post_web.dart @@ -2,40 +2,64 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import '../post/models/post_model.dart'; -import '../post/widgets/post.dart'; import 'loading_reddit.dart'; import 'sort_bottom_web.dart'; -import '../myprofile/models/myprofile_data.dart'; +import '../providers/profile_provider.dart'; +import '../post/widgets/post_list.dart'; class MyProfilePostWeb extends StatefulWidget { final String userName; - MyProfilePostWeb({ - Key? key, - required this.userName - }) : super(key: key); + MyProfilePostWeb({Key? key, required this.userName}) : super(key: key); @override State createState() => _MyProfilePostWebState(); } class _MyProfilePostWebState extends State { + int _page = 1; + + bool _isLoadMoreRunning = false; + bool _isInit = true; bool _isLoading = false; List? posts = []; + late ScrollController _scrollController; + //=====================================this function is used to======================================// + //=================Loading More Data====================// + void _loadMore() { + if (_isLoading == false && _isLoadMoreRunning == false) { + setState(() { + toggleLoadingMore(); // Display a progress indicator at the bottom + }); + setState(() { + _page += 1; + }); + // Increase _page by + + setState(() { + toggleLoadingMore(); + }); + } + } + //=====================================this function is used to======================================// + //=================Start loading More Data====================// + bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; + //=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override void didChangeDependencies() { if (_isInit) { setState(() { _isLoading = true; }); - // Provider.of(context, listen: false) - // .fetchProfilePosts('Amr') - // .then((value) { - // posts = Provider.of(context, listen: false) - // .gettingProfilePostData; - // setState(() { - // _isLoading = false; - // }); - // }); + Provider.of(context, listen: false) + .fetchProfilePosts(widget.userName, 'Hot', _page, 25, context) + .then((value) { + posts = Provider.of(context, listen: false) + .gettingProfilePostData; + setState(() { + _isLoading = false; + }); + }); } _isInit = false; super.didChangeDependencies(); @@ -43,91 +67,46 @@ class _MyProfilePostWebState extends State { @override Widget build(BuildContext context) { - return ListView( - scrollDirection: Axis.vertical, - children: [ - Expanded( - flex: 2, - child: Column( - children: [ - Container( - height: 6.h, - width: 50.w, - margin: EdgeInsets.only(left: 100, bottom: 10, top: 30), - child: SortBottomWeb(page: 1,userName: widget.userName), - color: Colors.white, - ), - Container( - margin: EdgeInsets.only(left: 100, bottom: 90, top: 30), - height: 30.h, - width: 50.w, - // color: Colors.white, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: [ - const Expanded( - child: ListTile( - title: Text('Post'), - ), - ), - if (!_isLoading) - ListView( - scrollDirection: Axis.vertical, - children: [ - SingleChildScrollView( - child: ListView.builder( - physics: const ClampingScrollPhysics(), - shrinkWrap: true, - itemBuilder: ((context, index) => Container( - margin: const EdgeInsets.only( - left: 100, bottom: 90, top: 30), - height: 30.h, - width: 50.w, - // color: Colors.white, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: const [ - Expanded( - child: ListTile( - title: Text('Post'), - ), - ), - ], - ), - ) - ]), - )), - itemCount: posts?.length, - ), - ), - ], - ) - ], + posts = Provider.of(context, listen: true) + .gettingProfilePostData; + return (_isLoading || _isLoadMoreRunning) + ? LoadingReddit() + : (posts != null) + ? + PostList( + leftMargin: 15.w, + rightMargin: 35.w, + topOfTheList:Container( + height: 10.h, + width: 50.h, + margin: EdgeInsets.only(left: 15.w,right: 37.w), + child: SortBottomWeb( + page: _page, + userName: widget.userName, ), - ) - ]), - ), - ], - ), - ), + ), + userName: widget.userName, + updateData: _loadMore, + data: posts as List, + type: 'profile', + ) - // ], - // ), - ], - ); + : Center( + child: Column( + children: [ + SizedBox( + height: 30.h, + ), + const Icon( + Icons.reddit, + size: 100, + ), + const Text( + 'Wow,such empty', + style: TextStyle(color: Colors.grey), + ) + ], + ), + ); } -} +} \ No newline at end of file diff --git a/lib/widgets/overview_myprofile_web.dart b/lib/widgets/overview_myprofile_web.dart index d1e415f1..5bc0542c 100644 --- a/lib/widgets/overview_myprofile_web.dart +++ b/lib/widgets/overview_myprofile_web.dart @@ -2,18 +2,22 @@ import 'package:flutter/material.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; import 'package:fluttericon/typicons_icons.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import '../myprofile/models/myprofile_data.dart'; import '../myprofile/widgets/myprofile_card_information_web.dart'; import '../widgets/loading_reddit.dart'; import '../widgets/sort_bottom_web.dart'; +import '../post/widgets/post_comment_list.dart'; class OverviewMyProfileWeb extends StatefulWidget { final MyProfileData loadProfile; final ScrollController scrollController; final String type; - OverviewMyProfileWeb( - {Key? key, required this.loadProfile, required this.scrollController,required this.type}) + OverviewMyProfileWeb( + {Key? key, + required this.loadProfile, + required this.scrollController, + required this.type}) : super(key: key); @override State createState() => _OverviewMyProfileWebState(); @@ -50,6 +54,8 @@ class _OverviewMyProfileWebState extends State { } ScrollController _scrollController = new ScrollController(); + //=====================================this function is used to======================================// + //=================Loading More Data====================// void _loadMore() { if (_isLoading == false && _isLoadMoreRunning == false) { setState(() { @@ -66,6 +72,8 @@ class _OverviewMyProfileWebState extends State { } } +//=====================================this function is used to======================================// + //=================Start loading More Data====================// bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; @override @@ -75,6 +83,8 @@ class _OverviewMyProfileWebState extends State { _scrollController = ScrollController()..addListener(_loadMore); } +//=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override Future didChangeDependencies() async { // TODO: implement didChangeDependencies @@ -113,147 +123,50 @@ class _OverviewMyProfileWebState extends State { Widget build(BuildContext context) { commentsAndPosts = Provider.of(context, listen: true) .gettingPostCommentData; - return ListView( - scrollDirection: Axis.vertical, - controller: widget.scrollController, - children: [ - Row( - // mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - flex: 2, - child: Column( - children: [ - SizedBox( - height: 4.h, + return (_isLoading || _isLoadMoreRunning) + ? const LoadingReddit() + : (commentsAndPosts == null || commentsAndPosts!.isEmpty) + ? Center( + child: Column( + children: [ + SizedBox( + height: 30.h, + ), + const Icon( + Icons.reddit, + size: 100, + color: Colors.black, + ), + const Text( + 'Wow,such empty', + style: TextStyle(color: Colors.grey), + ) + ], + ), + ) + : PostCommentList( + leftMargin: 15.w, + rightMargin: 35.w, + topOfTheList: Container( + height: 65.h, + width: 50.h, + margin: EdgeInsets.only(left: 15.w), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + MyProfileCardInformationWeb( + loadProfile: widget.loadProfile), + SortBottomWeb( + page: 1, + userName: widget.loadProfile.userName.toString()), + ], ), - Container( - height: 6.h, - width: 50.w, - margin: EdgeInsets.only(left: 100, bottom: 10, top: 30), - child: SortBottomWeb( - page: 1, - userName: widget.loadProfile.userName.toString()), - color: Colors.white, - ), - (_isLoading || _isLoadMoreRunning) - ? const LoadingReddit() - : (commentsAndPosts == null || commentsAndPosts!.isEmpty) - ? Center( - child: Column( - children: [ - SizedBox( - height: 30.h, - ), - const Icon( - Icons.reddit, - size: 100, - color: Colors.black, - ), - const Text( - 'Wow,such empty', - style: TextStyle(color: Colors.grey), - ) - ], - ), - ) - : SingleChildScrollView( - child: ListView.builder( - physics: const ClampingScrollPhysics(), - shrinkWrap: true, - scrollDirection: Axis.vertical, - itemBuilder: ((context, index) => InkWell( - child: Container( - padding: const EdgeInsets.all(10), - width: double.infinity, - margin: EdgeInsets.all(20), - color: const Color.fromARGB( - 255, 255, 255, 255), - child: Column( - children: [ - (commentsAndPosts![index]['type'] == - 'comment') - ? ListTile( - title: Text( - commentsAndPosts![index] - ['data'] - .title - .toString()), - subtitle: Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - mainAxisAlignment: - MainAxisAlignment - .start, - children: [ - Text.rich( - TextSpan( - children: [ - TextSpan( - text: - '${(commentsAndPosts![index]['data'].ownerType == 'User') ? 'u/' : 'r/'}${commentsAndPosts![index]['data'].owner}.${dateOfcomment(commentsAndPosts![index]['data'].createdAt.toString())} .${commentsAndPosts![index]['data'].votes}'), - const WidgetSpan( - child: Icon( - Typicons.up, - size: 15, - )), - ], - ), - ), - Text(commentsAndPosts![ - index]['data'] - .text - .toString()), - ], - ), - ) - : Container( - margin: EdgeInsets.only( - left: 100, - bottom: 90, - top: 30), - height: 30.h, - width: 50.w, - decoration: BoxDecoration( - color: Colors.white, - border: Border.all( - color: Colors.blue, - width: 3, - )), - child: Column(children: [ - Expanded( - child: Row( - children: const [ - Expanded( - child: ListTile( - title: Text( - 'Post'), - ), - ), - ], - ), - ) - ]), - ), - const Divider() - ], - ), - ), - onTap: () {}, - )), - itemCount: commentsAndPosts?.length, - ), - ) - ], - ), - ), - MyProfileCardInformationWeb(loadProfile: widget.loadProfile), - ], - ), - ], - ); + ), + userName: widget.loadProfile.userName.toString(), + updateData: _loadMore, + data: commentsAndPosts as List>, + type: 'Profile', + ); } } diff --git a/lib/widgets/post_sort_bottom.dart b/lib/widgets/post_sort_bottom.dart index c12142f5..769e3084 100644 --- a/lib/widgets/post_sort_bottom.dart +++ b/lib/widgets/post_sort_bottom.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import '../providers/subreddit_posts_provider.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; @@ -50,12 +50,6 @@ class PostSortBottomState extends State bool _isLoading = false; @override void didChangeDependencies() { - if (_isInit) { - print( - '===============================insideSortButton============================='); - // tappedIndex = 0; - } - _isInit = false; super.didChangeDependencies(); } diff --git a/lib/widgets/profile_comments.dart b/lib/widgets/profile_comments.dart index 3d929596..273c4482 100644 --- a/lib/widgets/profile_comments.dart +++ b/lib/widgets/profile_comments.dart @@ -2,7 +2,7 @@ import 'package:responsive_sizer/responsive_sizer.dart'; import 'package:provider/provider.dart'; import 'package:fluttericon/typicons_icons.dart'; import 'package:flutter/material.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import '../models/comments_data.dart'; import '../widgets/loading_reddit.dart'; @@ -45,6 +45,8 @@ class ProfileCommentsState extends State { } ScrollController _scrollController = new ScrollController(); + //=====================================this function is used to======================================// + //=================Loading More Data====================// void loadMore() async { if (_isLoading == false && _isLoadMoreRunning == false && @@ -73,19 +75,20 @@ class ProfileCommentsState extends State { }); } } - +//=====================================this function is used to======================================// + //=================Start loading More Data====================// bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; @override void initState() { // TODO: implement initState super.initState(); - print( - '==============================inint profile Post======================'); _scrollController = ScrollController()..addListener(loadMore); } - +//=====================================this function is used to======================================// + //=================Loading Data for first time====================// + @override Future didChangeDependencies() async { // TODO: implement didChangeDependencies @@ -154,7 +157,7 @@ class ProfileCommentsState extends State { padding: const EdgeInsets.all(10), width: double.infinity, // height: 15.h, - color: const Color.fromARGB(255, 255, 255, 255), + color: Color.fromARGB(255, 107, 38, 38), child: Column( children: [ ListTile( diff --git a/lib/widgets/profile_posts.dart b/lib/widgets/profile_posts.dart index faa756d0..7b083ee9 100644 --- a/lib/widgets/profile_posts.dart +++ b/lib/widgets/profile_posts.dart @@ -8,7 +8,7 @@ import 'package:responsive_sizer/responsive_sizer.dart'; import './post_sort_bottom.dart'; import '../post/widgets/post_list.dart'; import 'package:provider/provider.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import '../post/models/post_model.dart'; // import '..' @@ -35,6 +35,8 @@ class ProfilePostsState extends State { bool _isLoading = false; List? posts = []; late ScrollController _scrollController; + //=====================================this function is used to======================================// + //=================Loading More Data====================// void _loadMore() { if (_isLoading == false && _isLoadMoreRunning == false) { setState(() { @@ -50,19 +52,20 @@ class ProfilePostsState extends State { }); } } - +//=====================================this function is used to======================================// + //=================Start loading More Data====================// + bool toggleLoadingMore() => _isLoadMoreRunning = !_isLoadMoreRunning; @override void initState() { // TODO: implement initState super.initState(); - print( - '==============================inint profile Post======================'); - print(widget.userName); - // _scrollController = ScrollController()..addListener(_loadMore); - } + } +//=====================================this function is used to======================================// + //=================Loading Data for first time====================// + @override void didChangeDependencies() { if (_isInit) { diff --git a/lib/widgets/sort_bottom_web.dart b/lib/widgets/sort_bottom_web.dart index 8eb96ef8..7fa99c80 100644 --- a/lib/widgets/sort_bottom_web.dart +++ b/lib/widgets/sort_bottom_web.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../providers/Profile_provider.dart'; +import '../providers/profile_provider.dart'; import 'package:responsive_sizer/responsive_sizer.dart'; class SortBottomWeb extends StatefulWidget { @@ -27,7 +27,7 @@ class SortBottomWebState extends State { return Container( height: 10.h, width: 50.w, - margin: const EdgeInsets.only(left: 30), + // margin: const EdgeInsets.only(left: 30), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -37,7 +37,7 @@ class SortBottomWebState extends State { color: Colors.white, // width: 10.w, height: 8.h, - margin: const EdgeInsets.only(left: 5), + // margin: const EdgeInsets.only(left: 5), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, diff --git a/lib/widgets/subreddit_about.dart b/lib/widgets/subreddit_about.dart index 8ca78af5..2e85401b 100644 --- a/lib/widgets/subreddit_about.dart +++ b/lib/widgets/subreddit_about.dart @@ -25,17 +25,17 @@ class _SubredditAboutState extends State { child: ListView(scrollDirection: Axis.vertical, children: [ Container( color: Colors.white, - margin: EdgeInsets.only(top: 120), - padding: EdgeInsets.only(left: 10), + margin: const EdgeInsets.only(top: 120), + padding: const EdgeInsets.only(left: 10), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( - margin: EdgeInsets.all(10), - child: Text('Subreddit Rules', + margin: const EdgeInsets.all(10), + child: const Text('Subreddit Rules', style: TextStyle(fontWeight: FontWeight.bold))), - Divider(), + const Divider(), _renderrules(), ], ), @@ -52,25 +52,25 @@ class _SubredditAboutState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( - margin: EdgeInsets.all(4), - padding: EdgeInsets.all(3), + margin: const EdgeInsets.all(4), + padding: const EdgeInsets.all(3), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text('Moderators', + const Text('Moderators', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 15)), IconButton( onPressed: () => Navigator.pushNamed( context, ContactModMessageScreen.routeName), - icon: Icon( + icon: const Icon( Icons.mail_outlined, color: Colors.grey, )), ], )), - Divider(), + const Divider(), Expanded( child: ListView.builder( itemCount: widget.moderators.length, diff --git a/lib/widgets/subreddit_copy_share.dart b/lib/widgets/subreddit_copy_share.dart index 6bae8296..d1ec2a0f 100644 --- a/lib/widgets/subreddit_copy_share.dart +++ b/lib/widgets/subreddit_copy_share.dart @@ -23,7 +23,6 @@ class CopyShare extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, - // mainAxisSize: MainAxisSize.min, children: [ const BarWidget(), Container( diff --git a/lib/widgets/subreddit_join_button_web.dart b/lib/widgets/subreddit_join_button_web.dart index 64ea3dcb..e9438461 100644 --- a/lib/widgets/subreddit_join_button_web.dart +++ b/lib/widgets/subreddit_join_button_web.dart @@ -7,13 +7,9 @@ import './custom_snack_bar.dart'; class SubredditJoinButtonWeb extends StatefulWidget { bool isJoined; - //String dropDownValue; String communityName; - //IconData icon; SubredditJoinButtonWeb( {required this.isJoined, - //required this.icon, - //required this.dropDownValue, required this.communityName}); @override @@ -35,7 +31,6 @@ class SubredditJoinButtonWebState extends State { return Container( width: 35.w, height: 6.h, - // color: Colors.yellow, child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -81,11 +76,12 @@ class SubredditJoinButtonWebState extends State { ], )); } + // ===================================the next two function used to===========================================// +//==================to join subreddit===========================// +//communityName==> commuintyUserName you want to join Future subscribe(BuildContext context) async { - print( - '===============================Subcribe=================================='); - bool sub = await Provider.of(context, listen: false) + bool sub = await Provider.of(context, listen: false) .joinAndDisjoinSubreddit(widget.communityName, 'sub', context); if (sub) { setState(() { @@ -103,14 +99,16 @@ class SubredditJoinButtonWebState extends State { } bool join() { - isJoinedstate = false; + isJoinedstate = true; return isJoinedstate; } - + // ===================================the next three function used to===========================================// +//==================to disjoin of subreddit===========================// +// have two option one:leave subreddit two: cancel +//communityName==> commuintyUserName you want to leave + Future unSubescribe(BuildContext ctx) async { - print( - '===============================Un Subcribe=================================='); - bool unSub = await Provider.of(context, listen: false) + bool unSub = await Provider.of(context, listen: false) .joinAndDisjoinSubreddit(widget.communityName, 'unsub', context); if (unSub) { setState(() { diff --git a/lib/widgets/subreddit_posts.dart b/lib/widgets/subreddit_posts.dart index 3a02202d..f83766b6 100644 --- a/lib/widgets/subreddit_posts.dart +++ b/lib/widgets/subreddit_posts.dart @@ -30,6 +30,9 @@ class _SubredditPosts extends State { bool _isLoading = false; List? posts = []; late ScrollController _scrollController; + //=====================================this function is used to======================================// + //=================Loading More Data====================// + void _loadMore() { if (_isLoading == false && _isLoadMoreRunning == false) { setState(() { @@ -52,7 +55,8 @@ class _SubredditPosts extends State { super.initState(); _scrollController = ScrollController()..addListener(_loadMore); } - +//=====================================this function is used to======================================// + //=================Loading Data for first time====================// @override void didChangeDependencies() async { if (_isInit) { @@ -121,35 +125,5 @@ class _SubredditPosts extends State { data: posts as List, type: 'community', ); - // ListView( - // controller: _scrollController, - // scrollDirection: Axis.vertical, - // physics: const ClampingScrollPhysics(), - // addAutomaticKeepAlives: true, - // shrinkWrap: true, - // children: [ - // PostSortBottom( - // page: _page, - // type: 'Subreddit', - // routeNamePop: widget.routeNamePop, - // userName: subredditName - // //_dropDownValue, _icon - // ), - // //Select the type of Posts - - // SingleChildScrollView( - // child: ListView.builder( - // physics: const ClampingScrollPhysics(), - // shrinkWrap: true, - // itemBuilder: ((context, index) => Post.community( - // data: posts![index], - // inView: false, - // updateDate: () {}, - // )), - // itemCount: posts?.length, - // ), - // ) - // ], - // ); } } diff --git a/linux/.gitignore b/linux/.gitignore deleted file mode 100644 index d3896c98..00000000 --- a/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt deleted file mode 100644 index ea1493e8..00000000 --- a/linux/CMakeLists.txt +++ /dev/null @@ -1,138 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "web") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.example.web") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd0164..00000000 --- a/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 1560fc80..00000000 --- a/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,19 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include -#include - -void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) pasteboard_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "PasteboardPlugin"); - pasteboard_plugin_register_with_registrar(pasteboard_registrar); - g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); - url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); -} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47b..00000000 --- a/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 5a3c3882..00000000 --- a/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - pasteboard - url_launcher_linux -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/linux/main.cc b/linux/main.cc deleted file mode 100644 index e7c5c543..00000000 --- a/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/linux/my_application.cc b/linux/my_application.cc deleted file mode 100644 index 15be13ed..00000000 --- a/linux/my_application.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "web"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "web"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/linux/my_application.h b/linux/my_application.h deleted file mode 100644 index 72271d5e..00000000 --- a/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore deleted file mode 100644 index 746adbb6..00000000 --- a/macos/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -# Flutter-related -**/Flutter/ephemeral/ -**/Pods/ - -# Xcode-related -**/dgph -**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig deleted file mode 100644 index c2efd0b6..00000000 --- a/macos/Flutter/Flutter-Debug.xcconfig +++ /dev/null @@ -1 +0,0 @@ -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig deleted file mode 100644 index c2efd0b6..00000000 --- a/macos/Flutter/Flutter-Release.xcconfig +++ /dev/null @@ -1 +0,0 @@ -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift deleted file mode 100644 index faaa29a7..00000000 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// Generated file. Do not edit. -// - -import FlutterMacOS -import Foundation - -import device_info_plus -import firebase_core -import firebase_messaging -import flutter_local_notifications -import pasteboard -import path_provider_macos -import shared_preferences_macos -import sqflite -import url_launcher_macos -import wakelock_macos - -func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { - DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) - FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin")) - FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin")) - FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) - PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin")) - PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) - SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) - SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) - UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) - WakelockMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockMacosPlugin")) -} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index ac7fe6d7..00000000 --- a/macos/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,572 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXAggregateTarget section */ - 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { - isa = PBXAggregateTarget; - buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; - buildPhases = ( - 33CC111E2044C6BF0003C045 /* ShellScript */, - ); - dependencies = ( - ); - name = "Flutter Assemble"; - productName = FLX; - }; -/* End PBXAggregateTarget section */ - -/* Begin PBXBuildFile section */ - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC111A2044C6BA0003C045; - remoteInfo = FLX; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 33CC110E2044A8840003C045 /* Bundle Framework */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Bundle Framework"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* web.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "web.app"; sourceTree = BUILT_PRODUCTS_DIR; }; - 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; - 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; - 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; - 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; - 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; - 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 33CC10EA2044A3C60003C045 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 33BA886A226E78AF003329D5 /* Configs */ = { - isa = PBXGroup; - children = ( - 33E5194F232828860026EE4D /* AppInfo.xcconfig */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, - ); - path = Configs; - sourceTree = ""; - }; - 33CC10E42044A3C60003C045 = { - isa = PBXGroup; - children = ( - 33FAB671232836740065AC1E /* Runner */, - 33CEB47122A05771004F2AC0 /* Flutter */, - 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - ); - sourceTree = ""; - }; - 33CC10EE2044A3C60003C045 /* Products */ = { - isa = PBXGroup; - children = ( - 33CC10ED2044A3C60003C045 /* web.app */, - ); - name = Products; - sourceTree = ""; - }; - 33CC11242044D66E0003C045 /* Resources */ = { - isa = PBXGroup; - children = ( - 33CC10F22044A3C60003C045 /* Assets.xcassets */, - 33CC10F42044A3C60003C045 /* MainMenu.xib */, - 33CC10F72044A3C60003C045 /* Info.plist */, - ); - name = Resources; - path = ..; - sourceTree = ""; - }; - 33CEB47122A05771004F2AC0 /* Flutter */ = { - isa = PBXGroup; - children = ( - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, - ); - path = Flutter; - sourceTree = ""; - }; - 33FAB671232836740065AC1E /* Runner */ = { - isa = PBXGroup; - children = ( - 33CC10F02044A3C60003C045 /* AppDelegate.swift */, - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, - 33E51913231747F40026EE4D /* DebugProfile.entitlements */, - 33E51914231749380026EE4D /* Release.entitlements */, - 33CC11242044D66E0003C045 /* Resources */, - 33BA886A226E78AF003329D5 /* Configs */, - ); - path = Runner; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 33CC10EC2044A3C60003C045 /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 33CC10E92044A3C60003C045 /* Sources */, - 33CC10EA2044A3C60003C045 /* Frameworks */, - 33CC10EB2044A3C60003C045 /* Resources */, - 33CC110E2044A8840003C045 /* Bundle Framework */, - 3399D490228B24CF009A79C7 /* ShellScript */, - ); - buildRules = ( - ); - dependencies = ( - 33CC11202044C79F0003C045 /* PBXTargetDependency */, - ); - name = Runner; - productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* web.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33CC10E52044A3C60003C045 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1300; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 33CC10EC2044A3C60003C045 = { - CreatedOnToolsVersion = 9.2; - LastSwiftMigration = 1100; - ProvisioningStyle = Automatic; - SystemCapabilities = { - com.apple.Sandbox = { - enabled = 1; - }; - }; - }; - 33CC111A2044C6BA0003C045 = { - CreatedOnToolsVersion = 9.2; - ProvisioningStyle = Manual; - }; - }; - }; - buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33CC10E42044A3C60003C045; - productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33CC10EC2044A3C60003C045 /* Runner */, - 33CC111A2044C6BA0003C045 /* Flutter Assemble */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 33CC10EB2044A3C60003C045 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3399D490228B24CF009A79C7 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - ); - outputFileListPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; - }; - 33CC111E2044C6BF0003C045 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - Flutter/ephemeral/FlutterInputs.xcfilelist, - ); - inputPaths = ( - Flutter/ephemeral/tripwire, - ); - outputFileListPaths = ( - Flutter/ephemeral/FlutterOutputs.xcfilelist, - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 33CC10E92044A3C60003C045 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; - targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 33CC10F52044A3C60003C045 /* Base */, - ); - name = MainMenu.xib; - path = Runner; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 338D0CE9231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Profile; - }; - 338D0CEA231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Profile; - }; - 338D0CEB231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Profile; - }; - 33CC10F92044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33CC10FA2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.11; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; - 33CC10FC2044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - }; - name = Debug; - }; - 33CC10FD2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Release; - }; - 33CC111C2044C6BA0003C045 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 33CC111D2044C6BA0003C045 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10F92044A3C60003C045 /* Debug */, - 33CC10FA2044A3C60003C045 /* Release */, - 338D0CE9231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10FC2044A3C60003C045 /* Debug */, - 33CC10FD2044A3C60003C045 /* Release */, - 338D0CEA231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC111C2044C6BA0003C045 /* Debug */, - 33CC111D2044C6BA0003C045 /* Release */, - 338D0CEB231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 33CC10E52044A3C60003C045 /* Project object */; -} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index df0c1df5..00000000 --- a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 1d526a16..00000000 --- a/macos/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift deleted file mode 100644 index d53ef643..00000000 --- a/macos/Runner/AppDelegate.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Cocoa -import FlutterMacOS - -@NSApplicationMain -class AppDelegate: FlutterAppDelegate { - override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - return true - } -} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index a2ec33f1..00000000 --- a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "images" : [ - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_16.png", - "scale" : "1x" - }, - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "2x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "1x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_64.png", - "scale" : "2x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_128.png", - "scale" : "1x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "2x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "1x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "1x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_1024.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png deleted file mode 100644 index 82b6f9d9..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png deleted file mode 100644 index 13b35eba..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png deleted file mode 100644 index 0a3f5fa4..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png deleted file mode 100644 index bdb57226..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png deleted file mode 100644 index f083318e..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png deleted file mode 100644 index 326c0e72..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png deleted file mode 100644 index 2f1632cf..00000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and /dev/null differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib deleted file mode 100644 index 80e867a4..00000000 --- a/macos/Runner/Base.lproj/MainMenu.xib +++ /dev/null @@ -1,343 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig deleted file mode 100644 index 99dd48ff..00000000 --- a/macos/Runner/Configs/AppInfo.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -// Application-level settings for the Runner target. -// -// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the -// future. If not, the values below would default to using the project name when this becomes a -// 'flutter create' template. - -// The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = web - -// The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.example.web - -// The copyright displayed in application information -PRODUCT_COPYRIGHT = Copyright © 2022 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig deleted file mode 100644 index 36b0fd94..00000000 --- a/macos/Runner/Configs/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Debug.xcconfig" -#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig deleted file mode 100644 index dff4f495..00000000 --- a/macos/Runner/Configs/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Release.xcconfig" -#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig deleted file mode 100644 index 42bcbf47..00000000 --- a/macos/Runner/Configs/Warnings.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings -GCC_WARN_UNDECLARED_SELECTOR = YES -CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES -CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE -CLANG_WARN__DUPLICATE_METHOD_MATCH = YES -CLANG_WARN_PRAGMA_PACK = YES -CLANG_WARN_STRICT_PROTOTYPES = YES -CLANG_WARN_COMMA = YES -GCC_WARN_STRICT_SELECTOR_MATCH = YES -CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES -CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES -GCC_WARN_SHADOW = YES -CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements deleted file mode 100644 index dddb8a30..00000000 --- a/macos/Runner/DebugProfile.entitlements +++ /dev/null @@ -1,12 +0,0 @@ - - - - - com.apple.security.app-sandbox - - com.apple.security.cs.allow-jit - - com.apple.security.network.server - - - diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist deleted file mode 100644 index 4789daa6..00000000 --- a/macos/Runner/Info.plist +++ /dev/null @@ -1,32 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIconFile - - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSMinimumSystemVersion - $(MACOSX_DEPLOYMENT_TARGET) - NSHumanReadableCopyright - $(PRODUCT_COPYRIGHT) - NSMainNibFile - MainMenu - NSPrincipalClass - NSApplication - - diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift deleted file mode 100644 index 2722837e..00000000 --- a/macos/Runner/MainFlutterWindow.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Cocoa -import FlutterMacOS - -class MainFlutterWindow: NSWindow { - override func awakeFromNib() { - let flutterViewController = FlutterViewController.init() - let windowFrame = self.frame - self.contentViewController = flutterViewController - self.setFrame(windowFrame, display: true) - - RegisterGeneratedPlugins(registry: flutterViewController) - - super.awakeFromNib() - } -} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements deleted file mode 100644 index 852fa1a4..00000000 --- a/macos/Runner/Release.entitlements +++ /dev/null @@ -1,8 +0,0 @@ - - - - - com.apple.security.app-sandbox - - - diff --git a/pubspec.lock b/pubspec.lock index 3ac2aede..fd1e980b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -351,6 +351,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.0+1" + draw_graph: + dependency: "direct main" + description: + name: draw_graph + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" dropdown_search: dependency: "direct main" description: @@ -358,6 +365,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "5.0.5" + editable: + dependency: "direct main" + description: + name: editable + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" email_validator: dependency: "direct main" description: @@ -608,6 +622,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "6.1.7" + flutter_recaptcha_v3: + dependency: "direct main" + description: + name: flutter_recaptcha_v3 + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.3" flutter_staggered_grid_view: dependency: "direct main" description: @@ -1507,6 +1528,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.9.5" + webview_flutter_plus: + dependency: transitive + description: + name: webview_flutter_plus + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.4" webview_flutter_wkwebview: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 4abe4b5a..4d022bc1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -54,6 +54,9 @@ dependencies: responsive_sizer: ^3.1.1 intl: ^0.17.0 provider: ^6.0.3 + animated_tree_view: ^1.0.0 + buttons_tabbar: ^1.3.6 + flutter_staggered_grid_view: ^0.6.2 mockito: ^5.3.2 build_runner: ^2.3.2 dartdoc: ^6.1.2 @@ -87,9 +90,8 @@ dependencies: url: https://github.com/Amr146/link_preview_generator.git expandable_page_view: ^1.0.17 flutter_html: ^2.1.1 - animated_tree_view: ^1.0.0 - buttons_tabbar: ^1.3.6 - flutter_staggered_grid_view: ^0.6.2 + responsive_framework: ^0.2.0 + device_preview: ^1.1.0 flutter_recaptcha_v3: ^0.1.2 draw_graph: ^1.0.0 editable: ^2.0.0 @@ -231,6 +233,7 @@ flutter: - assets/images/up-arrow.png - assets/images/default-img.png - assets/images/reddit.png + - assets/images/ # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg @@ -258,4 +261,7 @@ flutter: # weight: 700 # # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages \ No newline at end of file + # see https://flutter.dev/custom-fonts/#from-packages + + + diff --git a/test/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button_test.dart b/test/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button_test.dart index 06dff201..0adaa818 100644 --- a/test/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button_test.dart +++ b/test/moderated_subreddit/widgets/moderated_subreddit_pop_up_menu_button_test.dart @@ -13,6 +13,16 @@ void main() { int result = subredditpopupButtonState.chooseNotificationType(1); expect(result, 1); }); + test('Subscribe ', () { + // TODO: Implement test + bool result = subredditpopupButtonState.changeJoinStatus(); + expect(result, true); + }); + test('UnSubcribe ', () { + // TODO: Implement test + bool result = subredditpopupButtonState.changeDisJoinStatus(); + expect(result, false); + }); }, ); } diff --git a/test/other_profile/widgets/follow_button_test.dart b/test/other_profile/widgets/follow_button_test.dart new file mode 100644 index 00000000..af5adb54 --- /dev/null +++ b/test/other_profile/widgets/follow_button_test.dart @@ -0,0 +1,21 @@ +import 'package:flutter_test/flutter_test.dart'; +import '../../../lib/widgets/follow_button.dart'; +void main() { + group( + 'follow button ...', + () { + // final createCommunity = CreateCommunity(); + final followButtonsState = FollowButtonState(); + test('Follow test', () { + // TODO: Implement test + bool result = followButtonsState.followSucceeded(); + expect(result, true); + }); + test('unFollow', () { + // TODO: Implement test + bool result = followButtonsState.unFollowsucceeded(); + expect(result, false); + }); + }, + ); +} \ No newline at end of file diff --git a/test/other_profile/widgets/invite_button_test.dart b/test/other_profile/widgets/invite_button_test.dart deleted file mode 100644 index 5de2a396..00000000 --- a/test/other_profile/widgets/invite_button_test.dart +++ /dev/null @@ -1,19 +0,0 @@ -// import 'package:flutter_test/flutter_test.dart'; -// import 'package:post/other_profile/widgets/invite_button.dart'; -// import '../../other_profile/widgets/invite_button_test.dart'; -// void main() { -// group( -// 'invite button ...', -// () { -// // final createCommunity = CreateCommunity(); -// final inviteButtonState = InviteButtonState(); -// test('changePost', () { -// // TODO: Implement test -// int result = inviteButtonState.invite(context); -// expect(result, 1); -// }); - - -// }, -// ); -// } \ No newline at end of file diff --git a/test/widgets/barwidget_test.dart b/test/other_profile/widgets/pop_down_menu_test.dart similarity index 65% rename from test/widgets/barwidget_test.dart rename to test/other_profile/widgets/pop_down_menu_test.dart index 54d9c171..227d8716 100644 --- a/test/widgets/barwidget_test.dart +++ b/test/other_profile/widgets/pop_down_menu_test.dart @@ -1,7 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('barwidget ...', (tester) async { + testWidgets('pop down menu ...', (tester) async { // TODO: Implement test }); } \ No newline at end of file diff --git a/test/other_profile/widgets/position_other_profile_web_test.dart b/test/other_profile/widgets/position_other_profile_web_test.dart new file mode 100644 index 00000000..0d143cac --- /dev/null +++ b/test/other_profile/widgets/position_other_profile_web_test.dart @@ -0,0 +1,22 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:post/other_profile/widgets/position_other_profile_web.dart'; +import '../../other_profile/widgets/position_other_profile_web_test.dart'; +void main() { + group( + 'follow button web ...', + () { + // final createCommunity = CreateCommunity(); + final positionOtherProfileWebState =PositionOtherProfileWebState(); + test('Follow test', () { + // TODO: Implement test + bool result = positionOtherProfileWebState.followSucceeded(); + expect(result, true); + }); + test('unFollow', () { + // TODO: Implement test + bool result = positionOtherProfileWebState.unFollowsucceeded(); + expect(result, false); + }); + }, + ); +} \ No newline at end of file diff --git a/test/subreddit/widgets/subreddit_join_buttons_test.dart b/test/subreddit/widgets/subreddit_join_buttons_test.dart index 3bfe11ba..fc93603b 100644 --- a/test/subreddit/widgets/subreddit_join_buttons_test.dart +++ b/test/subreddit/widgets/subreddit_join_buttons_test.dart @@ -13,6 +13,7 @@ void main() { int result = subredditJoinButtonState.changeNotificationMode(1); expect(result, 1); }); + }, ); } diff --git a/test/widgets/myprofile_comment_web_test.dart b/test/widgets/myprofile_comment_web_test.dart new file mode 100644 index 00000000..ebddb744 --- /dev/null +++ b/test/widgets/myprofile_comment_web_test.dart @@ -0,0 +1,7 @@ +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('myprofile comment web ...', (tester) async { + // TODO: Implement test + }); +} \ No newline at end of file diff --git a/test/widgets/post_sort_bottom_test.dart b/test/widgets/post_sort_bottom_test.dart deleted file mode 100644 index 245d56ac..00000000 --- a/test/widgets/post_sort_bottom_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// import 'package:flutter_test/flutter_test.dart'; -// import 'package:post/subreddit/widgets/subreddit_join_buttons.dart'; -// import '../../lib/widgets/post_sort_bottom.dart'; - -// void main() { -// group( -// 'Post type buttons ...', -// () { -// // final createCommunity = CreateCommunity(); -// final posttypeButtonState = PostSortBottomState(); -// test('changePost', () { -// // TODO: Implement test -// int result = posttypeButtonState.choosePostType(1); -// expect(result, 1); -// }); - -// test('changetopPost', () { -// // TODO: Implement test -// int result = posttypeButtonState.chooseTimeOfTopPosts(2,1); -// expect(result, 1); -// }); -// }, -// ); -// } diff --git a/test/widgets/profile_comments_test.dart b/test/widgets/profile_comments_test.dart new file mode 100644 index 00000000..897e3165 --- /dev/null +++ b/test/widgets/profile_comments_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import '../../lib/widgets/profile_comments.dart'; +void main() { + group( + 'profile comments ...', + () { + // final createCommunity = CreateCommunity(); + final profileCommentsState = ProfileCommentsState(); + test('Comment date1', () { + // TODO: Implement test + String result = profileCommentsState.dateOfcomment('2022-09-24T14:15:22Z'); + expect(result, '3mon'); + }); + test('Comment date2', () { + // TODO: Implement test + String result = profileCommentsState.dateOfcomment('2021-08-24T14:15:22'); + expect(result, '1y'); + }); + test('Comment date3', () { + // TODO: Implement test + String result = profileCommentsState.dateOfcomment('2022-11-24T14:15:22Z'); + expect(result, '3w'); + }); + + test('Loading more comments', () { + // TODO: Implement test + bool result = profileCommentsState.toggleLoadingMore(); + expect(result, true); + }); + }, + ); +} diff --git a/test/widgets/profile_posts_test.dart b/test/widgets/profile_posts_test.dart new file mode 100644 index 00000000..b3fd885a --- /dev/null +++ b/test/widgets/profile_posts_test.dart @@ -0,0 +1,16 @@ +// import 'package:flutter_test/flutter_test.dart'; +// import '../../lib/widgets/profile_posts.dart'; +// void main() { +// group( +// 'profile posts ...', +// () { +// // final createCommunity = CreateCommunity(); +// final profilePostsState = ProfilePostsState(); +// test('Loading more comments', () { +// // TODO: Implement test +// bool result = profilePostsState.toggleLoadingMore(); +// expect(result, true); +// }); +// }, +// ); +// } diff --git a/test/widgets/subreddit_join_button_web_test.dart b/test/widgets/subreddit_join_button_web_test.dart index 0b4aa4cb..204b3f53 100644 --- a/test/widgets/subreddit_join_button_web_test.dart +++ b/test/widgets/subreddit_join_button_web_test.dart @@ -7,11 +7,17 @@ void main() { () { // final createCommunity = CreateCommunity(); final joinButtonState = SubredditJoinButtonWebState(); - test(' joinButtonSubredditWeb', () { + test(' disjoinButtonSubredditWeb', () { // TODO: Implement test bool result = joinButtonState.disJoin(); expect(result, false); }); + + test(' joinButtonSubredditWeb', () { + // TODO: Implement test + bool result = joinButtonState.join(); + expect(result, true); + }); }, ); } diff --git a/windows/.gitignore b/windows/.gitignore deleted file mode 100644 index d492d0d9..00000000 --- a/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ephemeral/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt deleted file mode 100644 index 4d39fc2b..00000000 --- a/windows/CMakeLists.txt +++ /dev/null @@ -1,101 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.14) -project(web LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "web") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Define build configuration option. -get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(IS_MULTICONFIG) - set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" - CACHE STRING "" FORCE) -else() - if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") - endif() -endif() -# Define settings for the Profile build mode. -set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") -set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") -set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") - -# Use Unicode for all projects. -add_definitions(-DUNICODE -D_UNICODE) - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_17) - target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") - target_compile_options(${TARGET} PRIVATE /EHsc) - target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") - target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Application build; see runner/CMakeLists.txt. -add_subdirectory("runner") - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# Support files are copied into place next to the executable, so that it can -# run in place. This is done instead of making a separate bundle (as on Linux) -# so that building and running from within Visual Studio will work. -set(BUILD_BUNDLE_DIR "$") -# Make the "install" step default, as it's required to run. -set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - CONFIGURATIONS Profile;Release - COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt deleted file mode 100644 index 930d2071..00000000 --- a/windows/flutter/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.14) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. -set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") - -# === Flutter Library === -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "flutter_export.h" - "flutter_windows.h" - "flutter_messenger.h" - "flutter_plugin_registrar.h" - "flutter_texture_registrar.h" -) -list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") -add_dependencies(flutter flutter_assemble) - -# === Wrapper === -list(APPEND CPP_WRAPPER_SOURCES_CORE - "core_implementations.cc" - "standard_codec.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_PLUGIN - "plugin_registrar.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_APP - "flutter_engine.cc" - "flutter_view_controller.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") - -# Wrapper sources needed for a plugin. -add_library(flutter_wrapper_plugin STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} -) -apply_standard_settings(flutter_wrapper_plugin) -set_target_properties(flutter_wrapper_plugin PROPERTIES - POSITION_INDEPENDENT_CODE ON) -set_target_properties(flutter_wrapper_plugin PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) -target_include_directories(flutter_wrapper_plugin PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_plugin flutter_assemble) - -# Wrapper sources needed for the runner. -add_library(flutter_wrapper_app STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_APP} -) -apply_standard_settings(flutter_wrapper_app) -target_link_libraries(flutter_wrapper_app PUBLIC flutter) -target_include_directories(flutter_wrapper_app PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_app flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") -set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} - ${PHONY_OUTPUT} - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" - windows-x64 $ - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} -) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 02129f58..00000000 --- a/windows/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,17 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include -#include - -void RegisterPlugins(flutter::PluginRegistry* registry) { - PasteboardPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("PasteboardPlugin")); - UrlLauncherWindowsRegisterWithRegistrar( - registry->GetRegistrarForPlugin("UrlLauncherWindows")); -} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h deleted file mode 100644 index dc139d85..00000000 --- a/windows/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake deleted file mode 100644 index 82731c9d..00000000 --- a/windows/flutter/generated_plugins.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - pasteboard - url_launcher_windows -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt deleted file mode 100644 index 17411a8a..00000000 --- a/windows/runner/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -cmake_minimum_required(VERSION 3.14) -project(runner LANGUAGES CXX) - -# Define the application target. To change its name, change BINARY_NAME in the -# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer -# work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} WIN32 - "flutter_window.cpp" - "main.cpp" - "utils.cpp" - "win32_window.cpp" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" - "Runner.rc" - "runner.exe.manifest" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add preprocessor definitions for the build version. -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") - -# Disable Windows macros that collide with C++ standard library functions. -target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") - -# Add dependency libraries and include directories. Add any application-specific -# dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) -target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc deleted file mode 100644 index 7d23baf9..00000000 --- a/windows/runner/Runner.rc +++ /dev/null @@ -1,121 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#pragma code_page(65001) -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_APP_ICON ICON "resources\\app_icon.ico" - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) -#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD -#else -#define VERSION_AS_NUMBER 1,0,0,0 -#endif - -#if defined(FLUTTER_VERSION) -#define VERSION_AS_STRING FLUTTER_VERSION -#else -#define VERSION_AS_STRING "1.0.0" -#endif - -VS_VERSION_INFO VERSIONINFO - FILEVERSION VERSION_AS_NUMBER - PRODUCTVERSION VERSION_AS_NUMBER - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_APP - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "com.example" "\0" - VALUE "FileDescription", "web" "\0" - VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "web" "\0" - VALUE "LegalCopyright", "Copyright (C) 2022 com.example. All rights reserved." "\0" - VALUE "OriginalFilename", "web.exe" "\0" - VALUE "ProductName", "web" "\0" - VALUE "ProductVersion", VERSION_AS_STRING "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp deleted file mode 100644 index b43b9095..00000000 --- a/windows/runner/flutter_window.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "flutter_window.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -FlutterWindow::FlutterWindow(const flutter::DartProject& project) - : project_(project) {} - -FlutterWindow::~FlutterWindow() {} - -bool FlutterWindow::OnCreate() { - if (!Win32Window::OnCreate()) { - return false; - } - - RECT frame = GetClientArea(); - - // The size here must match the window dimensions to avoid unnecessary surface - // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( - frame.right - frame.left, frame.bottom - frame.top, project_); - // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { - return false; - } - RegisterPlugins(flutter_controller_->engine()); - SetChildContent(flutter_controller_->view()->GetNativeWindow()); - return true; -} - -void FlutterWindow::OnDestroy() { - if (flutter_controller_) { - flutter_controller_ = nullptr; - } - - Win32Window::OnDestroy(); -} - -LRESULT -FlutterWindow::MessageHandler(HWND hwnd, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - // Give Flutter, including plugins, an opportunity to handle window messages. - if (flutter_controller_) { - std::optional result = - flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, - lparam); - if (result) { - return *result; - } - } - - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; - } - - return Win32Window::MessageHandler(hwnd, message, wparam, lparam); -} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h deleted file mode 100644 index 6da0652f..00000000 --- a/windows/runner/flutter_window.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef RUNNER_FLUTTER_WINDOW_H_ -#define RUNNER_FLUTTER_WINDOW_H_ - -#include -#include - -#include - -#include "win32_window.h" - -// A window that does nothing but host a Flutter view. -class FlutterWindow : public Win32Window { - public: - // Creates a new FlutterWindow hosting a Flutter view running |project|. - explicit FlutterWindow(const flutter::DartProject& project); - virtual ~FlutterWindow(); - - protected: - // Win32Window: - bool OnCreate() override; - void OnDestroy() override; - LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept override; - - private: - // The project to run. - flutter::DartProject project_; - - // The Flutter instance hosted by this window. - std::unique_ptr flutter_controller_; -}; - -#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp deleted file mode 100644 index e6bd2d5c..00000000 --- a/windows/runner/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include - -#include "flutter_window.h" -#include "utils.h" - -int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, - _In_ wchar_t *command_line, _In_ int show_command) { - // Attach to console when present (e.g., 'flutter run') or create a - // new console when running with a debugger. - if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { - CreateAndAttachConsole(); - } - - // Initialize COM, so that it is available for use in the library and/or - // plugins. - ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - - flutter::DartProject project(L"data"); - - std::vector command_line_arguments = - GetCommandLineArguments(); - - project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.CreateAndShow(L"web", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - } - - ::CoUninitialize(); - return EXIT_SUCCESS; -} diff --git a/windows/runner/resource.h b/windows/runner/resource.h deleted file mode 100644 index 66a65d1e..00000000 --- a/windows/runner/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Runner.rc -// -#define IDI_APP_ICON 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico deleted file mode 100644 index c04e20ca..00000000 Binary files a/windows/runner/resources/app_icon.ico and /dev/null differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest deleted file mode 100644 index a42ea768..00000000 --- a/windows/runner/runner.exe.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - PerMonitorV2 - - - - - - - - - - - - - - - diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp deleted file mode 100644 index f5bf9fa0..00000000 --- a/windows/runner/utils.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include - -#include - -void CreateAndAttachConsole() { - if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); - } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); - } - std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); - } -} - -std::vector GetCommandLineArguments() { - // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. - int argc; - wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - if (argv == nullptr) { - return std::vector(); - } - - std::vector command_line_arguments; - - // Skip the first argument as it's the binary name. - for (int i = 1; i < argc; i++) { - command_line_arguments.push_back(Utf8FromUtf16(argv[i])); - } - - ::LocalFree(argv); - - return command_line_arguments; -} - -std::string Utf8FromUtf16(const wchar_t* utf16_string) { - if (utf16_string == nullptr) { - return std::string(); - } - int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr); - std::string utf8_string; - if (target_length == 0 || target_length > utf8_string.max_size()) { - return utf8_string; - } - utf8_string.resize(target_length); - int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, utf8_string.data(), - target_length, nullptr, nullptr); - if (converted_length == 0) { - return std::string(); - } - return utf8_string; -} diff --git a/windows/runner/utils.h b/windows/runner/utils.h deleted file mode 100644 index 3879d547..00000000 --- a/windows/runner/utils.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef RUNNER_UTILS_H_ -#define RUNNER_UTILS_H_ - -#include -#include - -// Creates a console for the process, and redirects stdout and stderr to -// it for both the runner and the Flutter library. -void CreateAndAttachConsole(); - -// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string -// encoded in UTF-8. Returns an empty std::string on failure. -std::string Utf8FromUtf16(const wchar_t* utf16_string); - -// Gets the command line arguments passed in as a std::vector, -// encoded in UTF-8. Returns an empty std::vector on failure. -std::vector GetCommandLineArguments(); - -#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp deleted file mode 100644 index c10f08dc..00000000 --- a/windows/runner/win32_window.cpp +++ /dev/null @@ -1,245 +0,0 @@ -#include "win32_window.h" - -#include - -#include "resource.h" - -namespace { - -constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; - -// The number of Win32Window objects that currently exist. -static int g_active_window_count = 0; - -using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); - -// Scale helper to convert logical scaler values to physical using passed in -// scale factor -int Scale(int source, double scale_factor) { - return static_cast(source * scale_factor); -} - -// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. -// This API is only needed for PerMonitor V1 awareness mode. -void EnableFullDpiSupportIfAvailable(HWND hwnd) { - HMODULE user32_module = LoadLibraryA("User32.dll"); - if (!user32_module) { - return; - } - auto enable_non_client_dpi_scaling = - reinterpret_cast( - GetProcAddress(user32_module, "EnableNonClientDpiScaling")); - if (enable_non_client_dpi_scaling != nullptr) { - enable_non_client_dpi_scaling(hwnd); - FreeLibrary(user32_module); - } -} - -} // namespace - -// Manages the Win32Window's window class registration. -class WindowClassRegistrar { - public: - ~WindowClassRegistrar() = default; - - // Returns the singleton registar instance. - static WindowClassRegistrar* GetInstance() { - if (!instance_) { - instance_ = new WindowClassRegistrar(); - } - return instance_; - } - - // Returns the name of the window class, registering the class if it hasn't - // previously been registered. - const wchar_t* GetWindowClass(); - - // Unregisters the window class. Should only be called if there are no - // instances of the window. - void UnregisterWindowClass(); - - private: - WindowClassRegistrar() = default; - - static WindowClassRegistrar* instance_; - - bool class_registered_ = false; -}; - -WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; - -const wchar_t* WindowClassRegistrar::GetWindowClass() { - if (!class_registered_) { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kWindowClassName; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = GetModuleHandle(nullptr); - window_class.hIcon = - LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - window_class.hbrBackground = 0; - window_class.lpszMenuName = nullptr; - window_class.lpfnWndProc = Win32Window::WndProc; - RegisterClass(&window_class); - class_registered_ = true; - } - return kWindowClassName; -} - -void WindowClassRegistrar::UnregisterWindowClass() { - UnregisterClass(kWindowClassName, nullptr); - class_registered_ = false; -} - -Win32Window::Win32Window() { - ++g_active_window_count; -} - -Win32Window::~Win32Window() { - --g_active_window_count; - Destroy(); -} - -bool Win32Window::CreateAndShow(const std::wstring& title, - const Point& origin, - const Size& size) { - Destroy(); - - const wchar_t* window_class = - WindowClassRegistrar::GetInstance()->GetWindowClass(); - - const POINT target_point = {static_cast(origin.x), - static_cast(origin.y)}; - HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); - UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); - double scale_factor = dpi / 96.0; - - HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, - Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), - Scale(size.width, scale_factor), Scale(size.height, scale_factor), - nullptr, nullptr, GetModuleHandle(nullptr), this); - - if (!window) { - return false; - } - - return OnCreate(); -} - -// static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto window_struct = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(window_struct->lpCreateParams)); - - auto that = static_cast(window_struct->lpCreateParams); - EnableFullDpiSupportIfAvailable(window); - that->window_handle_ = window; - } else if (Win32Window* that = GetThisFromHandle(window)) { - return that->MessageHandler(window, message, wparam, lparam); - } - - return DefWindowProc(window, message, wparam, lparam); -} - -LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - if (quit_on_close_) { - PostQuitMessage(0); - } - return 0; - - case WM_DPICHANGED: { - auto newRectSize = reinterpret_cast(lparam); - LONG newWidth = newRectSize->right - newRectSize->left; - LONG newHeight = newRectSize->bottom - newRectSize->top; - - SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, - newHeight, SWP_NOZORDER | SWP_NOACTIVATE); - - return 0; - } - case WM_SIZE: { - RECT rect = GetClientArea(); - if (child_content_ != nullptr) { - // Size and position the child window. - MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top, TRUE); - } - return 0; - } - - case WM_ACTIVATE: - if (child_content_ != nullptr) { - SetFocus(child_content_); - } - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - OnDestroy(); - - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - if (g_active_window_count == 0) { - WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); - } -} - -Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - SetParent(content, window_handle_); - RECT frame = GetClientArea(); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -RECT Win32Window::GetClientArea() { - RECT frame; - GetClientRect(window_handle_, &frame); - return frame; -} - -HWND Win32Window::GetHandle() { - return window_handle_; -} - -void Win32Window::SetQuitOnClose(bool quit_on_close) { - quit_on_close_ = quit_on_close; -} - -bool Win32Window::OnCreate() { - // No-op; provided for subclasses. - return true; -} - -void Win32Window::OnDestroy() { - // No-op; provided for subclasses. -} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h deleted file mode 100644 index 17ba4311..00000000 --- a/windows/runner/win32_window.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef RUNNER_WIN32_WINDOW_H_ -#define RUNNER_WIN32_WINDOW_H_ - -#include - -#include -#include -#include - -// A class abstraction for a high DPI-aware Win32 Window. Intended to be -// inherited from by classes that wish to specialize with custom -// rendering and input handling -class Win32Window { - public: - struct Point { - unsigned int x; - unsigned int y; - Point(unsigned int x, unsigned int y) : x(x), y(y) {} - }; - - struct Size { - unsigned int width; - unsigned int height; - Size(unsigned int width, unsigned int height) - : width(width), height(height) {} - }; - - Win32Window(); - virtual ~Win32Window(); - - // Creates and shows a win32 window with |title| and position and size using - // |origin| and |size|. New windows are created on the default monitor. Window - // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size to will treat the width height passed in to this function - // as logical pixels and scale to appropriate for the default monitor. Returns - // true if the window was created successfully. - bool CreateAndShow(const std::wstring& title, - const Point& origin, - const Size& size); - - // Release OS resources associated with window. - void Destroy(); - - // Inserts |content| into the window tree. - void SetChildContent(HWND content); - - // Returns the backing Window handle to enable clients to set icon and other - // window properties. Returns nullptr if the window has been destroyed. - HWND GetHandle(); - - // If true, closing this window will quit the application. - void SetQuitOnClose(bool quit_on_close); - - // Return a RECT representing the bounds of the current client area. - RECT GetClientArea(); - - protected: - // Processes and route salient window messages for mouse handling, - // size change and DPI. Delegates handling of these to member overloads that - // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Called when CreateAndShow is called, allowing subclass window-related - // setup. Subclasses should return false if setup fails. - virtual bool OnCreate(); - - // Called when Destroy is called. - virtual void OnDestroy(); - - private: - friend class WindowClassRegistrar; - - // OS callback called by message pump. Handles the WM_NCCREATE message which - // is passed when the non-client area is being created and enables automatic - // non-client DPI scaling so that the non-client area automatically - // responsponds to changes in DPI. All other messages are handled by - // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Retrieves a class instance pointer for |window| - static Win32Window* GetThisFromHandle(HWND const window) noexcept; - - bool quit_on_close_ = false; - - // window handle for top level window. - HWND window_handle_ = nullptr; - - // window handle for hosted content. - HWND child_content_ = nullptr; -}; - -#endif // RUNNER_WIN32_WINDOW_H_