feat: feed page connected with backend

This commit is contained in:
sBubshait 2025-07-23 13:50:49 +03:00
parent 32cec6da12
commit 05fb7b19aa
3 changed files with 263 additions and 127 deletions

View File

@ -1,43 +1,67 @@
class Post { class PostCreator {
final String id; final String id;
final String body;
final String userId;
final String username;
final String displayName; final String displayName;
final DateTime createdAt;
final DateTime updatedAt;
Post({ PostCreator({
required this.id, required this.id,
required this.body,
required this.userId,
required this.username,
required this.displayName, required this.displayName,
required this.createdAt,
required this.updatedAt,
}); });
factory Post.fromJson(Map<String, dynamic> json) { factory PostCreator.fromJson(Map<String, dynamic> json) {
return Post( return PostCreator(
id: json['id'] ?? '', id: json['id']?.toString() ?? '',
body: json['body'] ?? '',
userId: json['userId'] ?? '',
username: json['username'] ?? '',
displayName: json['displayName'] ?? '', displayName: json['displayName'] ?? '',
createdAt: DateTime.parse(json['createdAt'] ?? DateTime.now().toIso8601String()),
updatedAt: DateTime.parse(json['updatedAt'] ?? DateTime.now().toIso8601String()),
); );
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'id': id, 'id': id,
'body': body,
'userId': userId,
'username': username,
'displayName': displayName, 'displayName': displayName,
'createdAt': createdAt.toIso8601String(), };
'updatedAt': updatedAt.toIso8601String(), }
}
class Post {
final String id;
final String creatorId;
final PostCreator creator;
final String body;
final int likes;
final int comments;
final DateTime creationDate;
Post({
required this.id,
required this.creatorId,
required this.creator,
required this.body,
required this.likes,
required this.comments,
required this.creationDate,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id']?.toString() ?? '',
creatorId: json['creatorId']?.toString() ?? '',
creator: PostCreator.fromJson(json['creator'] ?? {}),
body: json['body'] ?? '',
likes: int.tryParse(json['likes']?.toString() ?? '0') ?? 0,
comments: int.tryParse(json['comments']?.toString() ?? '0') ?? 0,
creationDate: DateTime.parse(json['creationDate'] ?? DateTime.now().toIso8601String()),
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'creatorId': creatorId,
'creator': creator.toJson(),
'body': body,
'likes': likes,
'comments': comments,
'creationDate': creationDate.toIso8601String(),
}; };
} }
} }

View File

@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../create_post_screen.dart'; import '../create_post_screen.dart';
import '../../services/post_service.dart';
import '../../models/post_models.dart';
import '../../utils/invitation_utils.dart';
class FeedPage extends StatefulWidget { class FeedPage extends StatefulWidget {
@override @override
@ -8,6 +11,40 @@ class FeedPage extends StatefulWidget {
class _FeedPageState extends State<FeedPage> { class _FeedPageState extends State<FeedPage> {
bool _isRefreshing = false; bool _isRefreshing = false;
bool _isLoading = true;
List<Post> _posts = [];
String _errorMessage = '';
@override
void initState() {
super.initState();
_loadPosts();
}
Future<void> _loadPosts() async {
setState(() {
_isLoading = true;
_errorMessage = '';
});
try {
final result = await PostService.getAllPosts();
setState(() {
if (result['success']) {
_posts = result['posts'];
} else {
_errorMessage = result['message'] ?? 'Failed to load posts';
}
_isLoading = false;
});
} catch (e) {
setState(() {
_errorMessage = 'Network error: $e';
_isLoading = false;
});
}
}
final List<Map<String, dynamic>> mockPosts = [ final List<Map<String, dynamic>> mockPosts = [
{ {
'id': '1', 'id': '1',
@ -79,29 +116,17 @@ class _FeedPageState extends State<FeedPage> {
child: Container(height: 1, color: Colors.grey[200]), child: Container(height: 1, color: Colors.grey[200]),
), ),
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
actions: [
IconButton(
onPressed: _loadPosts,
icon: Icon(Icons.refresh),
tooltip: 'Refresh',
),
],
), ),
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: _refreshFeed, onRefresh: _refreshFeed,
child: ListView.builder( child: _buildBody(),
padding: EdgeInsets.symmetric(vertical: 8),
itemCount: mockPosts.length,
itemBuilder: (context, index) {
return PostCard(
post: mockPosts[index],
onLikePressed: () {
setState(() {
if (mockPosts[index]['isLiked']) {
mockPosts[index]['likes']--;
mockPosts[index]['isLiked'] = false;
} else {
mockPosts[index]['likes']++;
mockPosts[index]['isLiked'] = true;
}
});
},
);
},
),
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: _navigateToCreatePost, onPressed: _navigateToCreatePost,
@ -111,17 +136,93 @@ class _FeedPageState extends State<FeedPage> {
); );
} }
Widget _buildBody() {
if (_isLoading) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF6A4C93)),
),
);
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 64,
color: Colors.grey[400],
),
SizedBox(height: 16),
Text(
_errorMessage,
style: TextStyle(
fontSize: 16,
color: Colors.grey[600],
),
textAlign: TextAlign.center,
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _loadPosts,
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xFF6A4C93),
foregroundColor: Colors.white,
),
child: Text('Try Again'),
),
],
),
);
}
if (_posts.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.post_add,
size: 64,
color: Colors.grey[400],
),
SizedBox(height: 16),
Text(
'Nothing here..',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.grey[600],
),
),
SizedBox(height: 8),
Text(
'Create the first post!',
style: TextStyle(
fontSize: 14,
color: Colors.grey[500],
),
),
],
),
);
}
return ListView.builder(
padding: EdgeInsets.symmetric(vertical: 8),
itemCount: _posts.length,
itemBuilder: (context, index) {
return PostCard(
post: _posts[index],
);
},
);
}
Future<void> _refreshFeed() async { Future<void> _refreshFeed() async {
setState(() { await _loadPosts();
_isRefreshing = true;
});
// Simulate API call for refreshing feed
await Future.delayed(Duration(seconds: 1));
setState(() {
_isRefreshing = false;
});
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
@ -139,59 +240,46 @@ class _FeedPageState extends State<FeedPage> {
// If post was created successfully, refresh the feed // If post was created successfully, refresh the feed
if (result == true) { if (result == true) {
_refreshFeed(); _loadPosts();
} }
} }
} }
class PostCard extends StatefulWidget { class PostCard extends StatefulWidget {
final Map<String, dynamic> post; final Post post;
final VoidCallback onLikePressed;
const PostCard({Key? key, required this.post, required this.onLikePressed}) const PostCard({Key? key, required this.post})
: super(key: key); : super(key: key);
@override @override
_PostCardState createState() => _PostCardState(); _PostCardState createState() => _PostCardState();
} }
class _PostCardState extends State<PostCard> class _PostCardState extends State<PostCard> {
with SingleTickerProviderStateMixin { Color _getAvatarColor(String displayName) {
late AnimationController _likeAnimationController; final colors = [
late Animation<double> _likeAnimation; Color(0xFF32B0A5),
Color(0xFF4600B9),
Color(0xFF6A4C93),
Color(0xFFFF6347),
Color(0xFF32CD32),
Color(0xFF9932CC),
];
@override int hash = displayName.hashCode;
void initState() { return colors[hash.abs() % colors.length];
super.initState();
_likeAnimationController = AnimationController(
duration: Duration(milliseconds: 300),
vsync: this,
);
_likeAnimation = Tween<double>(begin: 1.0, end: 1.3).animate(
CurvedAnimation(
parent: _likeAnimationController,
curve: Curves.elasticOut,
),
);
} }
@override String _getAvatarLetter(String displayName) {
void dispose() { return displayName.isNotEmpty ? displayName[0].toUpperCase() : '?';
_likeAnimationController.dispose();
super.dispose();
}
void _handleLike() {
widget.onLikePressed();
_likeAnimationController.forward().then((_) {
_likeAnimationController.reverse();
});
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = widget.post['user']; final creator = widget.post.creator;
final isLiked = widget.post['isLiked']; final avatarColor = _getAvatarColor(creator.displayName);
final avatarLetter = _getAvatarLetter(creator.displayName);
final relativeTime = InvitationUtils.getRelativeTime(widget.post.creationDate);
return Container( return Container(
margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8), margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
@ -215,9 +303,9 @@ class _PostCardState extends State<PostCard>
children: [ children: [
CircleAvatar( CircleAvatar(
radius: 20, radius: 20,
backgroundColor: user['avatar_color'], backgroundColor: avatarColor,
child: Text( child: Text(
user['avatar'], avatarLetter,
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -231,7 +319,7 @@ class _PostCardState extends State<PostCard>
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
user['displayName'], creator.displayName,
style: TextStyle( style: TextStyle(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
fontSize: 16, fontSize: 16,
@ -240,7 +328,7 @@ class _PostCardState extends State<PostCard>
), ),
SizedBox(height: 2), SizedBox(height: 2),
Text( Text(
widget.post['timestamp'], relativeTime,
style: TextStyle(color: Colors.grey[600], fontSize: 12), style: TextStyle(color: Colors.grey[600], fontSize: 12),
), ),
], ],
@ -258,7 +346,7 @@ class _PostCardState extends State<PostCard>
), ),
SizedBox(height: 12), SizedBox(height: 12),
Text( Text(
widget.post['content'], widget.post.body,
style: TextStyle( style: TextStyle(
fontSize: 15, fontSize: 15,
height: 1.4, height: 1.4,
@ -268,27 +356,20 @@ class _PostCardState extends State<PostCard>
SizedBox(height: 16), SizedBox(height: 16),
Row( Row(
children: [ children: [
AnimatedBuilder( IconButton(
animation: _likeAnimation, onPressed: () {
builder: (context, child) { ScaffoldMessenger.of(context).showSnackBar(
return Transform.scale( SnackBar(content: Text('Like feature coming soon!')),
scale: _likeAnimation.value, );
child: GestureDetector( },
onTap: _handleLike, icon: Icon(
child: Container( Icons.favorite_border,
padding: EdgeInsets.all(12), color: Colors.grey[600],
child: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
color: isLiked ? Colors.red : Colors.grey[600],
size: 24, size: 24,
), ),
), ),
),
);
},
),
Text( Text(
'${widget.post['likes']}', '${widget.post.likes}',
style: TextStyle( style: TextStyle(
color: Colors.grey[700], color: Colors.grey[700],
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
@ -297,9 +378,9 @@ class _PostCardState extends State<PostCard>
SizedBox(width: 16), SizedBox(width: 16),
IconButton( IconButton(
onPressed: () { onPressed: () {
ScaffoldMessenger.of( ScaffoldMessenger.of(context).showSnackBar(
context, SnackBar(content: Text('Comments feature coming soon!')),
).showSnackBar(SnackBar(content: Text('Comments pressed'))); );
}, },
icon: Icon( icon: Icon(
Icons.chat_bubble_outline, Icons.chat_bubble_outline,
@ -308,7 +389,7 @@ class _PostCardState extends State<PostCard>
), ),
), ),
Text( Text(
'${widget.post['comments']}', '${widget.post.comments}',
style: TextStyle( style: TextStyle(
color: Colors.grey[700], color: Colors.grey[700],
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
@ -317,9 +398,9 @@ class _PostCardState extends State<PostCard>
Spacer(), Spacer(),
IconButton( IconButton(
onPressed: () { onPressed: () {
ScaffoldMessenger.of( ScaffoldMessenger.of(context).showSnackBar(
context, SnackBar(content: Text('Share feature coming soon!')),
).showSnackBar(SnackBar(content: Text('Share pressed'))); );
}, },
icon: Icon( icon: Icon(
Icons.share_outlined, Icons.share_outlined,

View File

@ -3,6 +3,39 @@ import '../models/post_models.dart';
import 'http_service.dart'; import 'http_service.dart';
class PostService { class PostService {
static Future<Map<String, dynamic>> getAllPosts() async {
try {
final response = await HttpService.get('/posts/all');
final responseData = jsonDecode(response.body);
if (response.statusCode == 200) {
return {
'success': responseData['status'] ?? false,
'message': responseData['message'] ?? '',
'posts':
(responseData['data'] as List?)
?.map((post) => Post.fromJson(post))
.toList() ??
[],
};
} else {
return {
'success': false,
'message': responseData['message'] ?? 'Failed to fetch posts',
'posts': <Post>[],
};
}
} catch (e) {
print('Error fetching posts: $e');
return {
'success': false,
'message': 'Network error: $e',
'posts': <Post>[],
};
}
}
static Future<Map<String, dynamic>> createPost(String body) async { static Future<Map<String, dynamic>> createPost(String body) async {
try { try {
final createPostRequest = CreatePostRequest(body: body); final createPostRequest = CreatePostRequest(body: body);
@ -17,7 +50,9 @@ class PostService {
return { return {
'success': responseData['status'] ?? false, 'success': responseData['status'] ?? false,
'message': responseData['message'] ?? '', 'message': responseData['message'] ?? '',
'post': responseData['data'] != null ? Post.fromJson(responseData['data']) : null, 'post': responseData['data'] != null
? Post.fromJson(responseData['data'])
: null,
}; };
} else { } else {
return { return {
@ -28,11 +63,7 @@ class PostService {
} }
} catch (e) { } catch (e) {
print('Error creating post: $e'); print('Error creating post: $e');
return { return {'success': false, 'message': 'Network error: $e', 'post': null};
'success': false,
'message': 'Network error: $e',
'post': null,
};
} }
} }
} }