To transform your current product list into an Instagram-style post layout with Like and Comment buttons, and to handle the like functionality by communicating with the server, follow the steps below:
-
Update the UI Layout: Change the layout from a horizontal ListTile to a vertical Column to resemble an Instagram post. This involves placing the product image on top, followed by the product details, and then the action buttons (Like and Comment).
-
Add Like and Comment Buttons: Introduce IconButton widgets for Like and Comment actions. You'll manage the like state locally and send a request to the server when the Like button is pressed.
-
Handle Like Functionality: Implement functionality to toggle the like state and inform the server about the action. This can be done using a POST request to your server.
-
Optimize for State Management: To efficiently manage the like state for each product, consider creating a separate StatefulWidget for each product item.
Below is the updated code incorporating these changes:
1. Updated Product Model
First, modify the Product model to include a isLiked property to track the like state locally.
class Product {
// Existing properties...
bool isLiked;
Product({
// Existing parameters...
this.isLiked = false,
});
factory Product.fromJson(Map json) {
// Existing parsing logic...
return Product(
// Existing assignments...
isLiked: json['isLiked'] ?? false, // Assuming the server provides this
);
}
}
2. Create a Separate ProductItem Widget
Create a new StatefulWidget called ProductItem to handle the UI and state for each product individually.
class ProductItem extends StatefulWidget {
final Product product;
final String baseUrl;
ProductItem({required this.product, required this.baseUrl});
@override
_ProductItemState createState() => _ProductItemState();
}
class _ProductItemState extends State<ProductItem> {
late bool isLiked;
int likeCount;
_ProductItemState() : likeCount = 0;
@override
void initState() {
super.initState();
isLiked = widget.product.isLiked;
likeCount = widget.product.popularity; // Assuming 'popularity' can represent likes
}
Future<void> _toggleLike() async {
final newLikeStatus = !isLiked;
try {
final response = await http.post(
Uri.parse('${widget.baseUrl}/like'), // Replace with your endpoint
headers: {'Content-Type': 'application/json'},
body: json.encode({'objectID': widget.product.objectID, 'like': newLikeStatus}),
);
if (response.statusCode == 200) {
setState(() {
isLiked = newLikeStatus;
likeCount += newLikeStatus ? 1 : -1;
});
} else {
// Handle server errors
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to ${newLikeStatus ? 'like' : 'unlike'} the product')),
);
}
} catch (e) {
// Handle network errors
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('An error occurred: $e')),
);
}
}
void _onComment() {
// Handle comment action, e.g., navigate to comments page
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Comment feature not implemented yet')),
);
}
@override
Widget build(BuildContext context) {
String imageUrl = '${widget.baseUrl}/${widget.product.image}';
return Card(
elevation: 3,
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Image
CachedNetworkImage(
imageUrl: imageUrl,
placeholder: (context, url) => const AspectRatio(
aspectRatio: 1,
child: Center(child: CircularProgressIndicator()),
),
errorWidget: (context, url, error) => const Icon(Icons.error),
width: double.infinity,
height: 300,
fit: BoxFit.cover,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Name
Text(
widget.product.name,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
// Product Description
Text(
widget.product.description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Brand and Price
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Brand: ${widget.product.brand}',
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
'\$${widget.product.price.toStringAsFixed(2)}',
style: TextStyle(color: Colors.green[700], fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 4),
// Rating
Row(
children: List.generate(5, (index) {
if (index < widget.product.rating) {
return const Icon(Icons.star, color: Colors.orange, size: 16);
} else {
return const Icon(Icons.star_border, color: Colors.orange, size: 16);
}
}),
),
const SizedBox(height: 8),
// Action Buttons
Row(
children: [
IconButton(
icon: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
color: isLiked ? Colors.red : Colors.grey,
),
onPressed: _toggleLike,
),
Text('$likeCount'),
const SizedBox(width: 16),
IconButton(
icon: const Icon(Icons.comment, color: Colors.grey),
onPressed: _onComment,
),
Text('${widget.product.popularity}'), // Update this if you have comments count
],
),
],
),
),
],
),
);
}
}
3. Update the SearchPage to Use ProductItem
Modify the _buildProductItem method to utilize the new ProductItem widget.
Widget _buildProductItem(Product product) {
return ProductItem(product: product, baseUrl: _baseUrl);
}
4. Complete Updated Code
Here is the complete updated code with all modifications integrated:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert'; // For JSON decoding
import 'package:cached_network_image/cached_network_image.dart';
void main() {
runApp(SearchApp());
}
class SearchApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Search App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SearchPage(),
debugShowCheckedModeBanner: false,
);
}
}
class Product {
final String name;
final String description;
final String brand;
final List categories;
final Map hierarchicalCategories;
final String type;
final double price;
final String priceRange;
final String image;
final String url;
final bool freeShipping;
final int popularity;
final int rating;
final String objectID;
bool isLiked;
Product({
required this.name,
required this.description,
required this.brand,
required this.categories,
required this.hierarchicalCategories,
required this.type,
required this.price,
required this.priceRange,
required this.image,
required this.url,
required this.freeShipping,
required this.popularity,
required this.rating,
required this.objectID,
this.isLiked = false,
});
factory Product.fromJson(Map json) {
List categoriesFromJson = [];
if (json['categories'] != null) {
categoriesFromJson = List.from(json['categories']);
}
Map hierarchicalCategoriesFromJson = {};
if (json['hierarchicalCategories'] != null) {
json['hierarchicalCategories'].forEach((key, value) {
hierarchicalCategoriesFromJson[key] = value;
});
}
return Product(
name: json['name'] ?? '',
description: json['description'] ?? '',
brand: json['brand'] ?? '',
categories: categoriesFromJson,
hierarchicalCategories: hierarchicalCategoriesFromJson,
type: json['type'] ?? '',
price: (json['price'] as num?)?.toDouble() ?? 0.0,
priceRange: json['price_range'] ?? '',
image: json['image'] ?? '',
url: json['url'] ?? '',
freeShipping: json['free_shipping'] ?? false,
popularity: json['popularity'] ?? 0,
rating: json['rating'] ?? 0,
objectID: json['objectID'] ?? '',
isLiked: json['isLiked'] ?? false, // New property
);
}
}
class SearchPage extends StatefulWidget {
SearchPage({Key? key}) : super(key: key);
@override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
final TextEditingController _controller = TextEditingController();
List<Product> _searchResults = [];
bool _isLoading = false;
String _errorMessage = '';
// Replace 'localhost' with your machine's IP address if running on a physical device
final String _baseUrl = 'http://localhost:8000';
Future<void> _performSearch(String query) async {
setState(() {
_isLoading = true;
_errorMessage = '';
_searchResults = [];
});
final uri = Uri.parse('$_baseUrl/search').replace(queryParameters: {
'query': query,
'num': '50',
'question': 'None',
});
try {
final response = await http.get(uri);
if (response.statusCode == 200) {
// Parse JSON response
final List data = json.decode(response.body);
// Convert JSON to List<Product>
List<Product> products =
data.map((item) => Product.fromJson(item)).toList();
setState(() {
_searchResults = products;
});
} else {
setState(() {
_errorMessage = 'Error: ${response.statusCode}';
});
}
} catch (e) {
setState(() {
_errorMessage = 'An error occurred: $e';
});
} finally {
setState(() {
_isLoading = false;
});
}
}
void _onSearch() {
final query = _controller.text.trim();
if (query.isNotEmpty) {
_performSearch(query);
}
}
Widget _buildProductItem(Product product) {
return ProductItem(product: product, baseUrl: _baseUrl);
}
Widget _buildResults() {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_errorMessage.isNotEmpty) {
return Center(
child: Text(
_errorMessage,
style: const TextStyle(color: Colors.red),
));
} else if (_searchResults.isEmpty) {
return const Center(child: Text('No results found.'));
} else {
return Expanded(
child: ListView.builder(
itemCount: _searchResults.length,
itemBuilder: (context, index) {
return _buildProductItem(_searchResults[index]);
},
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Search Products'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'Search',
hintText: 'Enter search term',
border: OutlineInputBorder(),
),
onSubmitted: (value) => _onSearch(),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _onSearch,
child: const Text('Search'),
),
],
),
const SizedBox(height: 20),
_buildResults(),
],
),
));
}
}
class ProductItem extends StatefulWidget {
final Product product;
final String baseUrl;
ProductItem({required this.product, required this.baseUrl});
@override
_ProductItemState createState() => _ProductItemState();
}
class _ProductItemState extends State<ProductItem> {
late bool isLiked;
int likeCount;
_ProductItemState() : likeCount = 0;
@override
void initState() {
super.initState();
isLiked = widget.product.isLiked;
likeCount = widget.product.popularity; // Assuming 'popularity' can represent likes
}
Future<void> _toggleLike() async {
final newLikeStatus = !isLiked;
try {
final response = await http.post(
Uri.parse('${widget.baseUrl}/like'), // Replace with your endpoint
headers: {'Content-Type': 'application/json'},
body: json.encode({'objectID': widget.product.objectID, 'like': newLikeStatus}),
);
if (response.statusCode == 200) {
setState(() {
isLiked = newLikeStatus;
likeCount += newLikeStatus ? 1 : -1;
});
} else {
// Handle server errors
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to ${newLikeStatus ? 'like' : 'unlike'} the product')),
);
}
} catch (e) {
// Handle network errors
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('An error occurred: $e')),
);
}
}
void _onComment() {
// Handle comment action, e.g., navigate to comments page
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Comment feature not implemented yet')),
);
}
@override
Widget build(BuildContext context) {
String imageUrl = '${widget.baseUrl}/${widget.product.image}';
return Card(
elevation: 3,
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Image
CachedNetworkImage(
imageUrl: imageUrl,
placeholder: (context, url) => const AspectRatio(
aspectRatio: 1,
child: Center(child: CircularProgressIndicator()),
),
errorWidget: (context, url, error) => const Icon(Icons.error),
width: double.infinity,
height: 300,
fit: BoxFit.cover,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Name
Text(
widget.product.name,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
// Product Description
Text(
widget.product.description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Brand and Price
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Brand: ${widget.product.brand}',
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
'\$${widget.product.price.toStringAsFixed(2)}',
style: TextStyle(color: Colors.green[700], fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 4),
// Rating
Row(
children: List.generate(5, (index) {
if (index < widget.product.rating) {
return const Icon(Icons.star, color: Colors.orange, size: 16);
} else {
return const Icon(Icons.star_border, color: Colors.orange, size: 16);
}
}),
),
const SizedBox(height: 8),
// Action Buttons
Row(
children: [
IconButton(
icon: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
color: isLiked ? Colors.red : Colors.grey,
),
onPressed: _toggleLike,
),
Text('$likeCount'),
const SizedBox(width: 16),
IconButton(
icon: const Icon(Icons.comment, color: Colors.grey),
onPressed: _onComment,
),
Text('${widget.product.popularity}'), // Update this if you have comments count
],
),
],
),
),
],
),
);
}
}
5. Explanation of Changes
a. Product Model Enhancement
isLiked Property: Added a bool isLiked property to the Product model to track whether the user has liked the product. This can be initialized based on server data if available.
b. ProductItem Widget
- Purpose: Encapsulates the UI and state management for each product, making the code cleaner and more maintainable.
- State Management: Manages
isLiked and likeCount state locally.
- UI Structure:
- Image: Displayed at the top using
CachedNetworkImage for efficient image loading.
- Details: Product name, description, brand, price, and rating.
- Action Buttons: Like and Comment buttons with respective counts.
c. Like Button Functionality
- Toggle Like State: When the Like button is pressed, it toggles the
isLiked state.
- Server Communication: Sends a POST request to the server to inform about the like/unlike action. Adjust the endpoint (
'/like') as per your server's API.
- Error Handling: Shows a
SnackBar message if the request fails.
- UI Update: Updates the like icon and like count based on the response.
d. Comment Button Placeholder
- Future Implementation: Currently, pressing the Comment button shows a
SnackBar. You can later implement navigation to a comments page or a modal.
6. Server-Side Considerations
Ensure that your server has an endpoint to handle like actions. For example:
7. Testing on Physical Devices
- Localhost Issue: If you're testing on a physical device, replace
'http://localhost:8000' with your computer's local network IP address (e.g., 'http://192.168.1.100:8000') to ensure the device can reach the server.
8. Dependencies
Ensure you have the following dependencies in your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
http: ^0.13.5
cached_network_image: ^3.2.3
Run flutter pub get to install them.
9. Final Notes
- State Persistence: The current implementation manages like states locally. For persistent state across sessions, consider integrating user authentication and fetching the like status from the server during the search.
- Optimistic UI Updates: To enhance user experience, you can optimistically update the UI before receiving the server response, reverting if the request fails.
- Expand Functionality: Implement actual comment functionality, share options, and other social features to further mimic Instagram's capabilities.
With these changes, your Flutter app will now display products in an Instagram-like format with functional Like buttons that communicate with your server.