import 'package:teso/Classes/API%20Clasess/Post.dart'; import 'package:teso/Classes/Firebase/Comments.dart'; import 'package:teso/Classes/TesoUser.dart'; import 'package:teso/Pages/PageWidgets/Posts/user3P_commentTitle.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:teso/Classes/API%20Clasess/CommentsPost.dart'; import 'package:teso/Pages/PageWidgets/ChatScreen/bottomBar.dart'; import 'package:teso/providers/user_provider.dart'; import 'package:teso/util/consts.dart'; import 'package:intl/intl.dart'; import 'package:time_elapsed/time_elapsed.dart'; class CommentSection extends StatefulWidget { final Post postedAd; final TesoUser user; CommentSection({ Key key, @required this.postedAd, @required this.user, }) : assert(postedAd != null), assert(user != null), super(key: key); @override _CommentSectionState createState() => _CommentSectionState(); } class _CommentSectionState extends State { TextEditingController controller = new TextEditingController(); final ScrollController listScrollController = ScrollController(); List listMessage = []; int _limit = 20; final int _limitIncrement = 20; int total = 0; var userDocs; List latest = []; _scrollListener() { if (listScrollController.offset >= listScrollController.position.maxScrollExtent && !listScrollController.position.outOfRange) { print("reach the bottom"); setState(() { print("reach the bottom"); _limit += _limitIncrement; }); } if (listScrollController.offset <= listScrollController.position.minScrollExtent && !listScrollController.position.outOfRange) { print("reach the top"); setState(() { print("reach the top"); }); } } @override void initState() { super.initState(); listScrollController.addListener(_scrollListener); _listenComments(); FirebaseFirestore.instance .collection("users") .doc(widget.postedAd.publisherID) .get() .then((value) { setState(() { userDocs = value.data(); }); }); } @override void dispose() { controller.dispose(); listScrollController.dispose(); super.dispose(); } void sendComment(String text, int position) async { TesoUser user = Provider.of(context, listen: false).currentUser; if (controller.text.isNotEmpty) { CommentsPost comment = new CommentsPost(); SharedPreferences.getInstance().then((value) async { comment.postId = widget.postedAd.postID; comment.comment = text.trim(); comment.timestamp = DateTime.now().toIso8601String(); comment.commenterId = value.getString("id"); comment.commentId = "TESCPCM" + DateTime.now().toString() + value.getString("id"); setState(() { latest.add(FBComments( comment: comment.comment, commenterID: comment.commenterId, commentID: comment.commentId, commenter: user.username, postID: comment.postId, thumbnail: user.thumbnail_dp, timestamp: DateTime.now(), )); total++; }); }); Provider.of(context, listen: false).commentPost(comment); controller.clear(); } } _listenComments() { FirebaseFirestore.instance .collection('posts') .doc(widget.postedAd.postID) .collection("comments") .orderBy('timestamp') .snapshots() .listen((event) { if (mounted) { setState(() { total = event.docs.length; latest.clear(); }); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, centerTitle: true, title: Text( "$total comments", style: TextStyle( fontSize: 14, ), ), actions: [ IconButton( onPressed: () => Navigator.pop(context), icon: Icon( Icons.close, ), ), ], ), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: Stack( children: [ Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, margin: EdgeInsets.only(bottom: 60), child: StreamBuilder( stream: FirebaseFirestore.instance .collection('posts') .doc(widget.postedAd.postID) .collection("comments") .orderBy('timestamp') .limit(_limit) .snapshots(), builder: (context, snapshot) { if (snapshot.data == null && snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation( Theme.of(context).primaryColor))); } else if (snapshot.data.docs.length == 0) { if (widget.postedAd.title != null) { return Align( alignment: Alignment.topCenter, child: buildPostTile3P( context, widget.user, widget.postedAd), ); } else { return Container(); } } else { QuerySnapshot results = snapshot.data; listMessage = results.docs .map((e) => FBComments.fromJSON(e.data())) .toList(); if (latest.length != 0) { listMessage.addAll(latest); } return ListView.builder( padding: EdgeInsets.all(10.0), itemCount: listMessage.length, itemBuilder: (context, index) { var formattedDate = DateFormat("yyyy-MM-dd HH:mm:ss") .format(listMessage[index].timestamp); if (index == 0 && widget.postedAd.title != null) { return Column(children: [ buildPostTile3P( context, widget.user, widget.postedAd), Divider(), ListTile( leading: Container( width: 40, height: 40, decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( color: Colors.black, width: 1, )), child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(90.0), topRight: Radius.circular(90.0), bottomLeft: Radius.circular(90), bottomRight: Radius.circular(90), ), child: FadeInImage( height: 90, width: 90, fit: BoxFit.fill, image: NetworkImage(serverLocation + "api/pulldp/" + snapshot.data.docs[index] .data()['commenterID']), placeholder: AssetImage( "assets/images/tesoDP/dp1.png"), ), ), ), title: new RichText( text: new TextSpan( style: new TextStyle( fontSize: 14.0, color: Theme.of(context).primaryColorLight, ), children: [ new TextSpan( text: snapshot.data.docs[index] .data()['commenter'] + " ", style: new TextStyle( fontWeight: FontWeight.bold)), new TextSpan( text: snapshot.data.docs[index] .data()['comment']), ], ), ), subtitle: Text( TimeElapsed.fromDateTime( DateTime.parse(formattedDate)), ), ), ]); } return ListTile( leading: Container( width: 40, height: 40, decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( color: Colors.black, width: 1, )), child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(90.0), topRight: Radius.circular(90.0), bottomLeft: Radius.circular(90), bottomRight: Radius.circular(90), ), child: FadeInImage( height: 90, width: 90, fit: BoxFit.fill, image: NetworkImage(serverLocation + "api/pulldp/" + listMessage[index].commenterID), placeholder: AssetImage("assets/images/tesoDP/dp1.png"), ), ), ), title: new RichText( text: new TextSpan( style: new TextStyle( fontSize: 14.0, color: Theme.of(context).primaryColorLight, ), children: [ new TextSpan( text: listMessage[index].commenter + " ", style: new TextStyle( fontWeight: FontWeight.bold)), new TextSpan(text: listMessage[index].comment), ], ), ), subtitle: Text( TimeElapsed.fromDateTime( DateTime.parse(formattedDate)), ), ); }, // reverse: true, controller: listScrollController, ); } }, ), ), Align( alignment: Alignment.bottomCenter, child: buildBottom( context, controller, sendComment, ), ), ], ), ), ); } }