import 'package:comunic/enums/likes_type.dart'; import 'package:comunic/helpers/likes_helper.dart'; import 'package:comunic/helpers/users_helper.dart'; import 'package:comunic/lists/posts_list.dart'; import 'package:comunic/lists/users_list.dart'; import 'package:comunic/models/post.dart'; import 'package:comunic/ui/screens/conversation_screen.dart'; import 'package:comunic/ui/tiles/post_tile.dart'; import 'package:comunic/utils/intl_utils.dart'; import 'package:comunic/utils/ui_utils.dart'; import 'package:flutter/material.dart'; /// Posts list widget /// /// Displays a list of posts /// /// @author Pierre HUBERT class PostsListWidget extends StatefulWidget { final Future Function() getPostsList; const PostsListWidget({ Key key, @required this.getPostsList, }) : assert(getPostsList != null), super(key: key); @override State createState() => _PostsListWidgetState(); } class _PostsListWidgetState extends State { // Helpers final LikesHelper _likesHelper = LikesHelper(); final UsersHelper _usersHelper = UsersHelper(); // Class members PostsList _list; UsersList _users; set error(ErrorLevel err) => setState(() => _error = err); ErrorLevel _error = ErrorLevel.NONE; @override void didChangeDependencies() { super.didChangeDependencies(); _loadPostsList(); } void _loadError() => error = _list == null ? ErrorLevel.MAJOR : ErrorLevel.MINOR; /// Load the list of posts Future _loadPostsList() async { final list = await widget.getPostsList(); if (list == null) return _loadError(); final users = await _usersHelper.getList(list.usersID); if (users == null) return _loadError(); setState(() { _list = list; _users = users; }); } Widget _buildErrorCard() { return buildErrorCard(tr("Could not get the list of posts !")); } Widget _buildListView() { return ListView.builder( itemCount: _list.length, itemBuilder: (c, i) => PostTile( post: _list[i], usersInfo: _users, onTapLike: _onUpdateLike, ), ); } @override Widget build(BuildContext context) { if (_error == ErrorLevel.MAJOR) return _buildErrorCard(); if (_list == null) return buildCenteredProgressBar(); return _buildListView(); } /// Update like status Future _onUpdateLike(Post post) async { // Update liking status _likesHelper.setLiking( type: LikesType.POST, like: !post.userLikes, id: post.id, ); // Save new like status setState(() { post.userLikes = !post.userLikes; post.userLikes ? post.likes++ : post.likes--; }); } }