pelase make the whole design and theme the best like the… · The Chat Archive
Explore pelase make the whole design and theme the best like the best design and super cool and… Save Share Download ▾ Reportpelase make the whole design and theme the best like the best design and super cool and modern feel and make it wokring all of it
"""
// screens/cart_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../providers/cart_provider.dart';
class CartScreen extends StatelessWidget {
const CartScreen({super.key});
@override
Widget build(BuildContext context) {
final cart = Provider.of(context);
Show full message · 969 lines Assistant2024-10-22 09:21 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 22, 2024
Added to archive Nov 16, 2026
ID 01m7h41zd7fz52201qz478zg5nSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: d183c187911682e99140cdb5ed4b1c51
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
return Scaffold(
appBar: AppBar(title: const Text('Your Cart')),
body: cart.items.isEmpty
? const Center(
child: Text('Your cart is empty'),
)
: Column(
children: [
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: cart.items.length,
separatorBuilder: (context, index) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final entry = cart.items.entries.elementAt(index);
final food = entry.key;
final quantity = entry.value;
final subtotal = food.price * quantity;
return Card(
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
food.images.first,
width: 80,
height: 80,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) =>
const Icon(Icons.error, size: 80),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
food.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'₹${food.price.toStringAsFixed(2)} each',
style: TextStyle(
color: Theme.of(context).primaryColor,
),
),
const SizedBox(height: 8),
Row(
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: () => cart.removeItem(food),
),
Text(
quantity.toString(),
style: const TextStyle(fontSize: 16),
),
IconButton(
icon: const Icon(Icons.add_circle_outline),
onPressed: () => cart.addItem(food),
),
],
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'₹${subtotal.toStringAsFixed(2)}',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
IconButton(
icon: const Icon(Icons.delete, color: Colors.redAccent),
onPressed: () => _confirmRemove(context, cart, food),
),
],
),
],
),
),
);
},
),
),
// Cart Summary
Padding(
padding: const EdgeInsets.all(16),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSummaryRow('Subtotal', cart.total),
const SizedBox(height: 8),
// You can add more details like taxes or discounts here
const Divider(),
const SizedBox(height: 8),
_buildSummaryRow(
'Total',
cart.total,
isTotal: true,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Implement checkout functionality
_checkout(context, cart.total);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
backgroundColor: Colors.deepOrange,
),
child: const Center(
child: Text(
'Checkout',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
),
],
),
),
),
),
],
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton.icon(
onPressed: () {
final Uri phoneNumber = Uri.parse('tel:+1234567890'); // Replace with actual phone number
launchUrl(phoneNumber);
},
icon: const Icon(Icons.phone),
label: const Text('Call Restaurant'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
),
);
Widget _buildSummaryRow(String label, double amount, {bool isTotal = false}) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: TextStyle(
fontSize: isTotal ? 18 : 16,
fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
),
),
Text(
'₹${amount.toStringAsFixed(2)}',
style: TextStyle(
fontSize: isTotal ? 18 : 16,
fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
color: isTotal ? Colors.black : Colors.grey[700],
),
),
],
);
}
void _confirmRemove(BuildContext context, CartProvider cart, dynamic food) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Remove Item'),
content: const Text('Are you sure you want to remove this item from the cart?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text('Remove', style: TextStyle(color: Colors.red)),
onPressed: () {
cart.removeAllOfItem(food);
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _checkout(BuildContext context, double total) {
// Implement your checkout logic here
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Checkout'),
content: Text('Proceed to pay ₹${total.toStringAsFixed(2)}?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text('Confirm'),
onPressed: () {
// Implement payment processing
// For example, clear the cart and show success message
Provider.of(context, listen: false).clear();
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Payment successful! Thank you for your order.'),
),
);
},
),
],
);
},
);
}
}
"""
"""
// screens/food_details_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/food.dart';
import '../providers/cart_provider.dart';
import '../services/food_service.dart';
import './cart_screen.dart';
class FoodDetailsScreen extends StatefulWidget {
final Food food;
const FoodDetailsScreen({super.key, required this.food});
@override
State createState() => _FoodDetailsScreenState();
}
class _FoodDetailsScreenState extends State {
final _reviewController = TextEditingController();
final _nameController = TextEditingController();
bool _isLoading = false;
bool _showReviewForm = false;
List reviews = [];
final FoodService _foodService = FoodService();
double _currentRating = 0.0;
@override
void initState() {
super.initState();
_loadReviews();
}
Future _loadReviews() async {
try {
setState(() => _isLoading = true);
final fetchedReviews = await _foodService.getFoodReviews(widget.food.id);
setState(() {
reviews = fetchedReviews;
_isLoading = false;
});
} catch (e) {
setState(() => _isLoading = false);
_showErrorSnackBar('Failed to load reviews');
}
}
Future _submitReview() async {
if (_nameController.text.isEmpty || _reviewController.text.isEmpty || _currentRating == 0.0) {
_showErrorSnackBar('Please fill in all fields and provide a rating');
return;
}
code Copy code
try {
setState(() => _isLoading = true);
await _foodService.submitReview(
widget.food.id,
_currentRating,
_nameController.text,
_reviewController.text,
);
_nameController.clear();
_reviewController.clear();
setState(() {
_showReviewForm = false;
_currentRating = 0.0;
});
await _loadReviews();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Review submitted successfully')),
);
}
} catch (e) {
_showErrorSnackBar('Failed to submit review');
} finally {
setState(() => _isLoading = false);
}
void _showErrorSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
),
);
}
Widget _buildReviewForm() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Your Name',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _reviewController,
decoration: const InputDecoration(
labelText: 'Write a review',
border: OutlineInputBorder(),
),
maxLines: 3,
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: List.generate(5, (index) {
return IconButton(
icon: Icon(
Icons.star,
color: index < _currentRating ? Colors.amber : Colors.grey,
),
onPressed: () {
setState(() {
_currentRating = (index + 1).toDouble();
});
},
);
}),
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: _submitReview,
child: const Text('Submit Review'),
),
],
);
}
@override
Widget build(BuildContext context) {
final cartProvider = Provider.of(context);
final cartQuantity = cartProvider.items[widget.food] ?? 0;
code Copy code
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 300,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text(widget.food.name),
background: Stack(
fit: StackFit.expand,
children: [
Hero(
tag: 'food-${widget.food.id}',
child: Image.network(
widget.food.images.first,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => const Center(child: Icon(Icons.error)),
),
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black54],
),
),
),
],
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Name and Rating
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.food.name,
style: Theme.of(context).textTheme.headlineSmall,
),
),
if (widget.food.rating != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(20),
),
child: Row(
children: [
const Icon(Icons.star, size: 20, color: Colors.white),
const SizedBox(width: 4),
Text(
widget.food.rating!.toStringAsFixed(1),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
const SizedBox(height: 8),
// Price
Text(
'₹${widget.food.price.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
const SizedBox(height: 16),
// Description
Text(
widget.food.description,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 24),
// Reviews Section
Text(
'Reviews',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 16),
// Toggle "Write a Review" Button
ElevatedButton.icon(
onPressed: () {
setState(() => _showReviewForm = !_showReviewForm);
},
icon: const Icon(Icons.rate_review),
label: Text(_showReviewForm ? 'Cancel' : 'Write a Review'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
// Conditionally show the review form
if (_showReviewForm) ...[
const SizedBox(height: 8),
_buildReviewForm(),
const SizedBox(height: 16),
],
// Reviews List
if (_isLoading)
const Center(child: CircularProgressIndicator())
else if (reviews.isEmpty)
const Text('No reviews yet. Be the first to review!')
else
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: reviews.length,
itemBuilder: (context, index) {
final review = reviews[index];
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
title: Text(review['name'] ?? 'Anonymous'),
subtitle: Text(review['description']),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.star, color: Colors.amber),
Text(review['rating'].toString()),
],
),
),
);
},
),
],
),
),
),
],
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: cartQuantity == 0
? ElevatedButton(
onPressed: () {
cartProvider.addItem(widget.food);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Added to cart'),
behavior: SnackBarBehavior.floating,
),
);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
backgroundColor: Colors.deepOrangeAccent,
),
child: const Text(
'Add to Cart',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
)
: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.3),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 3),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: const Icon(Icons.remove),
onPressed: () {
cartProvider.removeItem(widget.food);
},
),
Text(
cartQuantity.toString(),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
cartProvider.addItem(widget.food);
},
),
const Spacer(),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
backgroundColor: Colors.deepOrange,
),
child: const Text(
'View Cart',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
);
@override
void dispose() {
_reviewController.dispose();
_nameController.dispose();
super.dispose();
}
}
"""
"""
// screens/home_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/food.dart';
import '../widgets/food_card.dart';
import '../screens/cart_screen.dart';
import '../services/food_service.dart';
import '../providers/cart_provider.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State createState() => _HomePageState();
}
class _HomePageState extends State with SingleTickerProviderStateMixin {
List foods = [];
String? filterCategory;
bool isLoading = true;
String? errorMessage;
final FoodService _foodService = FoodService();
late AnimationController _controller;
late Animation _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 800),
vsync: this,
);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
code Copy code
Future.microtask(() => _fetchFoods());
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future _fetchFoods() async {
setState(() {
isLoading = true;
errorMessage = null;
});
code Copy code
try {
final fetchedFoods = await _foodService.getFoods();
setState(() {
foods = fetchedFoods;
isLoading = false;
_controller.forward(); // Start the animation when data is loaded
});
} catch (e) {
setState(() {
errorMessage = 'Network error. Please check your connection.';
isLoading = false;
});
_showErrorSnackBar('Network error. Please check your connection.');
}
void _showErrorSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 4),
action: SnackBarAction(
label: 'Retry',
onPressed: _fetchFoods,
),
),
);
}
void _navigateToCart() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
}
void _updateFilter(String? newFilter) {
setState(() {
filterCategory = newFilter;
});
}
@override
Widget build(BuildContext context) {
final filteredFoods = filterCategory == null
? foods
: foods.where((food) => food.category.toLowerCase() == filterCategory).toList();
code Copy code
return Scaffold(
appBar: AppBar(
title: const Text('Restaurant Menu'),
actions: [
IconButton(
icon: const Icon(Icons.shopping_cart),
onPressed: _navigateToCart,
tooltip: 'View Cart',
),
],
),
body: RefreshIndicator(
onRefresh: _fetchFoods,
child: Column(
children: [
_buildFilterChips(),
Expanded(
child: isLoading
? const Center(child: CircularProgressIndicator())
: filteredFoods.isEmpty
? Center(
child: Text(errorMessage ?? 'No items found'),
)
: FadeTransition( // 'child' placed last
opacity: _animation,
child: GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: filteredFoods.length,
itemBuilder: (context, index) {
final food = filteredFoods[index];
return FoodCard(food: food);
},
),
),
),
],
),
),
floatingActionButton: AnimatedOpacity(
opacity: filteredFoods.any(
(food) => Provider.of<CartProvider>(context, listen: false).items.containsKey(food))
? 1.0
: 0.0,
duration: const Duration(milliseconds: 300),
child: FloatingActionButton(
onPressed: _navigateToCart,
backgroundColor: Colors.deepOrange,
tooltip: 'View Cart',
child: const Icon(Icons.shopping_cart),
),
),
);
Widget buildFilterChips() {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
ChoiceChip(
label: const Text('All'),
selected: filterCategory == null,
onSelected: ( ) => updateFilter(null),
),
const SizedBox(width: 8),
ChoiceChip(
label: const Text('Veg'),
selected: filterCategory == 'veg',
onSelected: ( ) => updateFilter('veg'),
),
const SizedBox(width: 8),
ChoiceChip(
label: const Text('Non-Veg'),
selected: filterCategory == 'non-veg',
onSelected: ( ) => _updateFilter('non-veg'),
),
],
),
),
);
}
}
"""
"""
// models/food.dart
class Food {
final String id;
final String name;
final double price;
final String description;
final String category;
final List images;
final double? rating;
Food({
required this.id,
required this.name,
required this.price,
required this.description,
required this.category,
required this.images,
this.rating,
});
factory Food.fromJson(Map<String, dynamic> json) {
return Food(
id: json['_id'],
name: json['name'],
price: json['price'].toDouble(),
description: json['description'],
category: json['category'],
images: List.from(json['images']),
rating: json['totalAverageRating']?.toDouble(),
);
}
}
"""
"""
// widgets/food_card.dart
import 'package:flutter/material.dart';
import '../models/food.dart';
import '../screens/food_details_screen.dart';
class FoodCard extends StatelessWidget {
final Food food;
const FoodCard({super.key, required this.food});
@override
Widget build(BuildContext context) {
return Card(
elevation: 3,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => FoodDetailsScreen(food: food),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Image
Expanded(
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: Image.network(
food.images.first,
fit: BoxFit.cover,
width: double.infinity,
errorBuilder: (context, error, stackTrace) => const Center(child: Icon(Icons.error)),
),
),
),
// Food Details
Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Name
Text(
food.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Rating and Price
Row(
children: [
if (food.rating != null) ...[
const Icon(Icons.star, size: 16, color: Colors.amber),
const SizedBox(width: 4),
Text(
food.rating!.toStringAsFixed(1),
style: const TextStyle(fontSize: 12),
),
const SizedBox(width: 8),
],
Text(
'₹${food.price.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
],
),
],
),
),
],
),
),
);
}
}
"""
Sure! Let's enhance your Flutter application with a modern, sleek design and ensure all components work seamlessly together. We'll focus on the following aspects:
Theme Enhancement : Utilize a cohesive color scheme, modern typography, and consistent styling across all screens.
UI Improvements : Incorporate updated widgets, animations, and responsive layouts to enhance user experience.
Code Optimization : Ensure the code is clean, maintainable, and follows best practices.
Below, I'll provide updated versions of your existing files with detailed explanations of the enhancements made.
1. Setting Up the Main Application
main.dart
First, ensure you have a main.dart file that sets up the application with the enhanced theme and integrates the Provider for state management.
dart Copy code
// main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'providers/cart_provider.dart';
import 'screens/home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// Define a custom theme
ThemeData _buildThemeData() {
return ThemeData(
primarySwatch: Colors.deepOrange,
colorScheme: ColorScheme.fromSwatch(
primarySwatch: Colors.deepOrange,
accentColor: Colors.amber,
).copyWith(
secondary: Colors.amber,
background: Colors.grey[100],
surface: Colors.white,
),
textTheme: const TextTheme(
headlineSmall: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
bodyMedium: TextStyle(
fontSize: 16,
color: Colors.black54,
),
),
appBarTheme: const AppBarTheme(
backgroundColor: Colors.white,
foregroundColor: Colors.black87,
elevation: 0,
centerTitle: true,
),
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: Colors.deepOrange,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepOrange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<CartProvider>(
create: (_) => CartProvider(),
),
// Add other providers here if needed
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Modern Restaurant App',
theme: _buildThemeData(),
home: const HomePage(),
),
);
}
}
Enhancements Made:
ThemeData Customization : Applied a consistent color scheme using deep orange and amber accents. Customized text themes for better readability and aesthetics.
AppBar Styling : Made the AppBar background white with dark text for a cleaner look.
Button Styling : Elevated buttons now have rounded corners and consistent padding.
Overall Aesthetics : Set a light grey background to create a subtle contrast with white surfaces.
2. Models
models/food.dart
Ensure your Food model is well-defined. No significant changes needed here, but ensure consistency with JSON parsing.
dart Copy code
// models/food.dart
class Food {
final String id;
final String name;
final double price;
final String description;
final String category;
final List<String> images;
final double? rating;
Food({
required this.id,
required this.name,
required this.price,
required this.description,
required this.category,
required this.images,
this.rating,
});
factory Food.fromJson(Map<String, dynamic> json) {
return Food(
id: json['_id'],
name: json['name'],
price: json['price'].toDouble(),
description: json['description'],
category: json['category'],
images: List<String>.from(json['images']),
rating: json['totalAverageRating']?.toDouble(),
);
}
}
3. Providers
providers/cart_provider.dart
Ensure your CartProvider is optimized for state management.
dart Copy code
// providers/cart_provider.dart
import 'package:flutter/material.dart';
import '../models/food.dart';
class CartProvider with ChangeNotifier {
final Map<Food, int> _items = {};
Map<Food, int> get items => _items;
double get total {
double total = 0.0;
_items.forEach((food, quantity) {
total += food.price * quantity;
});
return total;
}
void addItem(Food food) {
if (_items.containsKey(food)) {
_items[food] = _items[food]! + 1;
} else {
_items[food] = 1;
}
notifyListeners();
}
void removeItem(Food food) {
if (_items.containsKey(food)) {
if (_items[food]! > 1) {
_items[food] = _items[food]! - 1;
} else {
_items.remove(food);
}
notifyListeners();
}
}
void removeAllOfItem(Food food) {
if (_items.containsKey(food)) {
_items.remove(food);
notifyListeners();
}
}
void clear() {
_items.clear();
notifyListeners();
}
}
4. Services
Ensure your FoodService is properly set up to fetch data. If you're using a mock service or real API, adjust accordingly.
dart Copy code
// services/food_service.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/food.dart';
class FoodService {
final String _baseUrl = 'https://your-api-endpoint.com/api'; // Replace with your API endpoint
Future<List<Food>> getFoods() async {
final response = await http.get(Uri.parse('$_baseUrl/foods'));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
return data.map((json) => Food.fromJson(json)).toList();
} else {
throw Exception('Failed to load foods');
}
}
Future<List<dynamic>> getFoodReviews(String foodId) async {
final response = await http.get(Uri.parse('$_baseUrl/foods/$foodId/reviews'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load reviews');
}
}
Future<void> submitReview(String foodId, double rating, String name, String description) async {
final response = await http.post(
Uri.parse('$_baseUrl/foods/$foodId/reviews'),
headers: {'Content-Type': 'application/json'},
body: json.encode({
'rating': rating,
'name': name,
'description': description,
}),
);
if (response.statusCode != 201) {
throw Exception('Failed to submit review');
}
}
}
Note: Replace https://your-api-endpoint.com/api with your actual API endpoint.
5. Widgets
widgets/food_card.dart
Enhance the FoodCard with modern design elements, such as subtle shadows, better image handling, and interactive feedback.
Enhancements Made:
Container Styling : Added rounded corners and subtle shadows for a modern look.
Hero Animation : Implemented Hero animations for smooth image transitions between screens.
Image Loading : Added a loading indicator for image fetching and error handling.
Interactive Feedback : Wrapped the card with GestureDetector to provide interactive feedback on taps.
6. Screens
screens/home_page.dart
Enhance the Home Page with improved filter chips, animations, and responsive grid layout.
Enhancements Made:
Filter Chips Styling : Customized ChoiceChip with selected colors and text styles for better visibility.
Floating Action Button Visibility : Used Selector to efficiently rebuild only when the cart count changes.
Responsive Layout : Added padding and adjusted grid spacing for a cleaner layout.
Error Messages : Enhanced error messages with better styling for readability.
Animations : Maintained fade transitions for a smooth user experience.
screens/cart_screen.dart
Enhance the Cart Screen with modern design elements, better layout management, and interactive feedback.
Enhancements Made:
Button Styling : Increased border radius for a more modern look and adjusted padding for better touch targets.
Image Loading : Added a loading indicator for images to improve user experience.
Responsive Layout : Ensured elements are well-spaced and responsive across different screen sizes.
Interactive Elements : Enhanced deletion and checkout confirmations with styled dialogs.
Consistent Typography : Maintained consistent text styles for better readability.
screens/food_details_screen.dart
Enhance the Food Details Screen with better layout, animations, and interactive elements.
Enhancements Made:
SliverAppBar Styling : Customized the SliverAppBar with a gradient overlay for better text readability over images.
Review Section : Improved the layout and styling of the review form and review list. Added separators and consistent padding.
Conditional UI : Enhanced the display of the cart action section based on the quantity, with rounded containers and shadows.
Interactive Elements : Enhanced button styles and added snack bars for immediate feedback.
Responsive Design : Ensured the layout adjusts smoothly across different screen sizes.
7. Final Touches
Assets Management
Ensure you have placeholder images or actual images added to your project’s assets. Update your pubspec.yaml accordingly:
yaml Copy code
# pubspec.yaml
flutter:
assets:
- assets/images/ # Add your images here
Dependencies
Make sure to include necessary dependencies in your pubspec.yaml:
yaml Copy code
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
url_launcher: ^6.1.5
http: ^0.13.4
Run flutter pub get to fetch the packages.
8. Testing the Application
Ensure all components work seamlessly:
Home Page : Displays a grid of food items with filtering options.
Food Details : Shows detailed information, reviews, and allows adding to the cart.
Cart : Manages cart items, quantities, and checkout process.
Responsiveness : Test on different device sizes to ensure the layout adjusts appropriately.
Animations : Verify smooth transitions and interactive feedback.
Error Handling : Test network failures and form validations.
9. Conclusion
By incorporating these enhancements, your Flutter application will boast a modern, sleek design with improved user experience. The consistent theme, responsive layouts, and interactive elements ensure that users have a delightful experience while navigating through the app.
Feel free to further customize the theme, add more animations, or integrate additional features as per your requirements. Happy coding!
Show full message · 1,380 lines Copy first response
Not yet included in a published release.
// widgets/food_card.dart
import 'package:flutter/material.dart';
import '../models/food.dart';
import '../screens/food_details_screen.dart';
class FoodCard extends StatelessWidget {
final Food food;
const FoodCard({super.key, required this.food});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// Navigate to Food Details with a smooth transition
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => FoodDetailsScreen(food: food),
),
);
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
blurRadius: 10,
spreadRadius: 5,
offset: const Offset(0, 5),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Image with Hero animation
Expanded(
child: Hero(
tag: 'food-${food.id}',
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
child: Image.network(
food.images.first,
fit: BoxFit.cover,
width: double.infinity,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(child: CircularProgressIndicator());
},
errorBuilder: (context, error, stackTrace) => const Center(child: Icon(Icons.error)),
),
),
),
),
// Food Details
Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Name
Text(
food.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
// Rating and Price
Row(
children: [
if (food.rating != null) ...[
const Icon(Icons.star, size: 16, color: Colors.amber),
const SizedBox(width: 4),
Text(
food.rating!.toStringAsFixed(1),
style: const TextStyle(fontSize: 12, color: Colors.black54),
),
const SizedBox(width: 8),
],
Text(
'₹${food.price.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
],
),
],
),
),
],
),
),
);
}
}
// screens/home_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/food.dart';
import '../widgets/food_card.dart';
import './cart_screen.dart';
import '../services/food_service.dart';
import '../providers/cart_provider.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
List<Food> foods = [];
String? filterCategory;
bool isLoading = true;
String? errorMessage;
final FoodService _foodService = FoodService();
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 800),
vsync: this,
);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
Future.microtask(() => _fetchFoods());
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _fetchFoods() async {
setState(() {
isLoading = true;
errorMessage = null;
});
try {
final fetchedFoods = await _foodService.getFoods();
setState(() {
foods = fetchedFoods;
isLoading = false;
_controller.forward(); // Start the animation when data is loaded
});
} catch (e) {
setState(() {
errorMessage = 'Network error. Please check your connection.';
isLoading = false;
});
_showErrorSnackBar('Network error. Please check your connection.');
}
}
void _showErrorSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 4),
action: SnackBarAction(
label: 'Retry',
onPressed: _fetchFoods,
),
),
);
}
void _navigateToCart() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
}
void _updateFilter(String? newFilter) {
setState(() {
filterCategory = newFilter;
});
}
@override
Widget build(BuildContext context) {
final filteredFoods = filterCategory == null
? foods
: foods.where((food) => food.category.toLowerCase() == filterCategory).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Restaurant Menu'),
actions: [
IconButton(
icon: const Icon(Icons.shopping_cart),
onPressed: _navigateToCart,
tooltip: 'View Cart',
),
],
),
body: RefreshIndicator(
onRefresh: _fetchFoods,
child: Column(
children: [
_buildFilterChips(),
Expanded(
child: isLoading
? const Center(child: CircularProgressIndicator())
: filteredFoods.isEmpty
? Center(
child: Text(
errorMessage ?? 'No items found',
style: const TextStyle(fontSize: 16, color: Colors.black54),
),
)
: FadeTransition(
opacity: _animation,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: filteredFoods.length,
itemBuilder: (context, index) {
final food = filteredFoods[index];
return FoodCard(food: food);
},
),
),
),
),
],
),
),
floatingActionButton: Selector<CartProvider, int>(
selector: (_, cart) => cart.items.length,
builder: (context, cartCount, child) {
return AnimatedOpacity(
opacity: cartCount > 0 ? 1.0 : 0.0,
duration: const Duration(milliseconds: 300),
child: FloatingActionButton(
onPressed: _navigateToCart,
backgroundColor: Colors.deepOrange,
tooltip: 'View Cart',
child: const Icon(Icons.shopping_cart),
),
);
},
),
);
}
Widget _buildFilterChips() {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
ChoiceChip(
label: const Text('All'),
selected: filterCategory == null,
selectedColor: Theme.of(context).primaryColor,
onSelected: (_) => _updateFilter(null),
labelStyle: TextStyle(
color: filterCategory == null ? Colors.white : Colors.black87,
),
),
const SizedBox(width: 8),
ChoiceChip(
label: const Text('Veg'),
selected: filterCategory == 'veg',
selectedColor: Theme.of(context).primaryColor,
onSelected: (_) => _updateFilter('veg'),
labelStyle: TextStyle(
color: filterCategory == 'veg' ? Colors.white : Colors.black87,
),
),
const SizedBox(width: 8),
ChoiceChip(
label: const Text('Non-Veg'),
selected: filterCategory == 'non-veg',
selectedColor: Theme.of(context).primaryColor,
onSelected: (_) => _updateFilter('non-veg'),
labelStyle: TextStyle(
color: filterCategory == 'non-veg' ? Colors.white : Colors.black87,
),
),
],
),
),
);
}
}
// screens/cart_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../providers/cart_provider.dart';
class CartScreen extends StatelessWidget {
const CartScreen({super.key});
@override
Widget build(BuildContext context) {
final cart = Provider.of<CartProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Your Cart'),
),
body: cart.items.isEmpty
? const Center(
child: Text(
'Your cart is empty',
style: TextStyle(fontSize: 18, color: Colors.black54),
),
)
: Column(
children: [
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: cart.items.length,
separatorBuilder: (context, index) => const SizedBox(height: 12),
itemBuilder: (context, index) {
final entry = cart.items.entries.elementAt(index);
final food = entry.key;
final quantity = entry.value;
final subtotal = food.price * quantity;
return Card(
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
food.images.first,
width: 80,
height: 80,
fit: BoxFit.cover,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(child: CircularProgressIndicator());
},
errorBuilder: (context, error, stackTrace) =>
const Icon(Icons.error, size: 80),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
food.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'₹${food.price.toStringAsFixed(2)} each',
style: TextStyle(
color: Theme.of(context).primaryColor,
),
),
const SizedBox(height: 8),
Row(
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: () => cart.removeItem(food),
),
Text(
quantity.toString(),
style: const TextStyle(fontSize: 16),
),
IconButton(
icon: const Icon(Icons.add_circle_outline),
onPressed: () => cart.addItem(food),
),
],
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'₹${subtotal.toStringAsFixed(2)}',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
IconButton(
icon: const Icon(Icons.delete, color: Colors.redAccent),
onPressed: () => _confirmRemove(context, cart, food),
),
],
),
],
),
),
);
},
),
),
// Cart Summary
Padding(
padding: const EdgeInsets.all(16),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSummaryRow('Subtotal', cart.total),
const SizedBox(height: 8),
// You can add more details like taxes or discounts here
const Divider(),
const SizedBox(height: 8),
_buildSummaryRow(
'Total',
cart.total,
isTotal: true,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Implement checkout functionality
_checkout(context, cart.total);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
backgroundColor: Colors.deepOrange,
),
child: const Center(
child: Text(
'Checkout',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
),
],
),
),
),
),
],
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton.icon(
onPressed: () {
final Uri phoneNumber = Uri.parse('tel:+1234567890'); // Replace with actual phone number
launchUrl(phoneNumber);
},
icon: const Icon(Icons.phone),
label: const Text('Call Restaurant'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
),
);
}
Widget _buildSummaryRow(String label, double amount, {bool isTotal = false}) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: TextStyle(
fontSize: isTotal ? 18 : 16,
fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
),
),
Text(
'₹${amount.toStringAsFixed(2)}',
style: TextStyle(
fontSize: isTotal ? 18 : 16,
fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
color: isTotal ? Colors.black : Colors.grey[700],
),
),
],
);
}
void _confirmRemove(BuildContext context, CartProvider cart, dynamic food) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Remove Item'),
content: const Text('Are you sure you want to remove this item from the cart?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text('Remove', style: TextStyle(color: Colors.red)),
onPressed: () {
cart.removeAllOfItem(food);
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _checkout(BuildContext context, double total) {
// Implement your checkout logic here
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Checkout'),
content: Text('Proceed to pay ₹${total.toStringAsFixed(2)}?'),
actions: [
TextButton(
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text('Confirm'),
onPressed: () {
// Implement payment processing
// For example, clear the cart and show success message
Provider.of<CartProvider>(context, listen: false).clear();
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Payment successful! Thank you for your order.'),
),
);
},
),
],
);
},
);
}
}
// screens/food_details_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/food.dart';
import '../providers/cart_provider.dart';
import '../services/food_service.dart';
import './cart_screen.dart';
class FoodDetailsScreen extends StatefulWidget {
final Food food;
const FoodDetailsScreen({super.key, required this.food});
@override
State<FoodDetailsScreen> createState() => _FoodDetailsScreenState();
}
class _FoodDetailsScreenState extends State<FoodDetailsScreen> {
final _reviewController = TextEditingController();
final _nameController = TextEditingController();
bool _isLoading = false;
bool _showReviewForm = false;
List<dynamic> reviews = [];
final FoodService _foodService = FoodService();
double _currentRating = 0.0;
@override
void initState() {
super.initState();
_loadReviews();
}
Future<void> _loadReviews() async {
try {
setState(() => _isLoading = true);
final fetchedReviews = await _foodService.getFoodReviews(widget.food.id);
setState(() {
reviews = fetchedReviews;
_isLoading = false;
});
} catch (e) {
setState(() => _isLoading = false);
_showErrorSnackBar('Failed to load reviews');
}
}
Future<void> _submitReview() async {
if (_nameController.text.isEmpty || _reviewController.text.isEmpty || _currentRating == 0.0) {
_showErrorSnackBar('Please fill in all fields and provide a rating');
return;
}
try {
setState(() => _isLoading = true);
await _foodService.submitReview(
widget.food.id,
_currentRating,
_nameController.text,
_reviewController.text,
);
_nameController.clear();
_reviewController.clear();
setState(() {
_showReviewForm = false;
_currentRating = 0.0;
});
await _loadReviews();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Review submitted successfully')),
);
}
} catch (e) {
_showErrorSnackBar('Failed to submit review');
} finally {
setState(() => _isLoading = false);
}
}
void _showErrorSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
),
);
}
Widget _buildReviewForm() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Your Name',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _reviewController,
decoration: const InputDecoration(
labelText: 'Write a review',
border: OutlineInputBorder(),
),
maxLines: 3,
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: List.generate(5, (index) {
return IconButton(
icon: Icon(
Icons.star,
color: index < _currentRating ? Colors.amber : Colors.grey,
),
onPressed: () {
setState(() {
_currentRating = (index + 1).toDouble();
});
},
);
}),
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: _submitReview,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
backgroundColor: Colors.deepOrangeAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: const Text('Submit Review'),
),
],
);
}
@override
Widget build(BuildContext context) {
final cartProvider = Provider.of<CartProvider>(context);
final cartQuantity = cartProvider.items[widget.food] ?? 0;
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 300,
pinned: true,
backgroundColor: Colors.white,
flexibleSpace: FlexibleSpaceBar(
title: Text(
widget.food.name,
style: const TextStyle(color: Colors.black87, shadows: [
Shadow(
blurRadius: 10.0,
color: Colors.white,
offset: Offset(0, 0),
),
]),
),
background: Stack(
fit: StackFit.expand,
children: [
Hero(
tag: 'food-${widget.food.id}',
child: Image.network(
widget.food.images.first,
fit: BoxFit.cover,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return const Center(child: CircularProgressIndicator());
},
errorBuilder: (context, error, stackTrace) => const Center(child: Icon(Icons.error)),
),
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black54],
),
),
),
],
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Food Name and Rating
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.food.name,
style: Theme.of(context).textTheme.headlineSmall,
),
),
if (widget.food.rating != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(20),
),
child: Row(
children: [
const Icon(Icons.star, size: 20, color: Colors.white),
const SizedBox(width: 4),
Text(
widget.food.rating!.toStringAsFixed(1),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
const SizedBox(height: 8),
// Price
Text(
'₹${widget.food.price.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Theme.of(context).primaryColor,
),
),
const SizedBox(height: 16),
// Description
Text(
widget.food.description,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 24),
// Reviews Section
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Reviews',
style: Theme.of(context).textTheme.headlineSmall,
),
ElevatedButton.icon(
onPressed: () {
setState(() => _showReviewForm = !_showReviewForm);
},
icon: const Icon(Icons.rate_review),
label: Text(_showReviewForm ? 'Cancel' : 'Write a Review'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
],
),
const SizedBox(height: 16),
// Conditionally show the review form
if (_showReviewForm) ...[
_buildReviewForm(),
const SizedBox(height: 16),
],
// Reviews List
if (_isLoading)
const Center(child: CircularProgressIndicator())
else if (reviews.isEmpty)
const Text('No reviews yet. Be the first to review!')
else
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: reviews.length,
itemBuilder: (context, index) {
final review = reviews[index];
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
title: Text(review['name'] ?? 'Anonymous'),
subtitle: Text(review['description']),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.star, color: Colors.amber),
Text(review['rating'].toString()),
],
),
),
);
},
),
],
),
),
),
],
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: cartQuantity == 0
? ElevatedButton(
onPressed: () {
cartProvider.addItem(widget.food);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Added to cart'),
behavior: SnackBarBehavior.floating,
),
);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
backgroundColor: Colors.deepOrangeAccent,
),
child: const Text(
'Add to Cart',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
)
: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.3),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 3),
),
],
),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.remove),
onPressed: () {
cartProvider.removeItem(widget.food);
},
),
Text(
cartQuantity.toString(),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
cartProvider.addItem(widget.food);
},
),
const Spacer(),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
backgroundColor: Colors.deepOrange,
),
child: const Text(
'View Cart',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
);
}
@override
void dispose() {
_reviewController.dispose();
_nameController.dispose();
super.dispose();
}
}