Make a home page for an ecommerce website with posts similar to instagram. use getx…
- User
Make a home page for an ecommerce website with posts similar to instagram. use getx package with flutter. Also include a search option in bottom navigation bar. when it's pressed a new page with only search at the middle of the page should open. Break the code into multiple file for oragnisation. An example get request to server for building home page will look like this.
[ { "name": "Dell - 2-in-1 13.3" Touch-Screen Laptop - Intel Core i7 - 8GB Memory - 1TB Hard Drive - Silver Touch", "description": "Only at Best Buy Dell Convertible 2-in-1 Laptop: This compact, efficient laptop features a bright 13.3" touch-screen display supported by Intel® HD graphics, so you can immerse yourself in entertainment on the go. Sync with Bluetooth-enabled devices for simple streaming.", "brand": "Dell", "categories": [ "Computers & Tablets", "Laptops", "All Laptops", "PC Laptops" ], "hierarchicalCategories": { "lvl0": "Computers & Tablets", "lvl1": "Computers & Tablets > Laptops", "lvl2": "Computers & Tablets > Laptops > All Laptops", "lvl3": "Computers & Tablets > Laptops > All Laptops > PC Laptops" }, "type": "Notebooks", "price": 899.99, "price_range": "500 - 2000", "image": "images/9514008.jpg", "url": "http://www.bestbuy.com/site/dell-2-in-1-13-3-touch-screen-laptop-intel-core-i7-8gb-memory-1tb-hard-drive-silver-touch/9514008.p?id=1219704425967&skuId=9514008&cmp=RMX&ky=1uWSHMdQqBeVJB9cXgEke60s5EjfS6M1W", "free_shipping": true, "popularity": 7718, "rating": 4, "objectID": "9514008" }, { "name": "Dell - Inspiron 7000 Series 2-in-1 15.6" Touch-Screen Laptop - Intel Core i5 - 8GB Memory - 500GB Hard Drive - Foggy Night", "description": "Only at Best Buy Dell Inspiron 7000 Series Convertible 2-in-1 Laptop: This laptop's vivid Full HD touch-screen display makes it easy to navigate the Web, play games and watch movies at home or on the go. An HDMI output lets you connect to an external display, and Bluetooth enables simple pairing with compatible devices.", "brand": "Dell", "categories": [ "Computers & Tablets", "Laptops", "All Laptops", "PC Laptops" ], "hierarchicalCategories": { "lvl0": "Computers & Tablets", "lvl1": "Computers & Tablets > Laptops", "lvl2": "Computers & Tablets > Laptops > All Laptops", "lvl3": "Computers & Tablets > Laptops > All Laptops > PC Laptops" }, "type": "Notebooks", "price": 729.99, "price_range": "500 - 2000", "image": "images/9522015.jpg", "url": "http://www.bestbuy.com/site/dell-inspiron-7000-series-2-in-1-15-6-touch-screen-laptop-intel-core-i5-8gb-memory-500gb-hard-drive-foggy-night/9522015.p?id=1219704417467&skuId=9522015&cmp=RMX&ky=1uWSHMdQqBeVJB9cXgEke60s5EjfS6M1W", "free_shipping": false, "popularity": 7695, "rating": 5, "objectID": "9522015" } ]
- Assistant
Creating a well-structured Flutter eCommerce application using the GetX package involves organizing your code into multiple files for better maintainability and scalability. Below is a comprehensive guide to building a home page with Instagram-like posts, a search feature in the bottom navigation bar, and handling GET requests to fetch product data.
Table of Contents
- Project Structure
- pubspec.yaml Configuration
- Models
- Controllers
- Views
- Main File
- Assets Configuration
Project Structure
Organizing your project into folders improves readability and maintainability. Here's a suggested structure:
lib/ ├── controllers/ │ └── home_controller.dart ├── models/ │ └── product.dart ├── views/ │ ├── home_page.dart │ ├── search_page.dart │ └── widgets/ │ └── product_card.dart ├── main.dart assets/ └── images/ ├── 9514008.jpg └── 9522015.jpg
pubspec.yaml Configuration
Firstly, ensure you have the necessary dependencies in your
pubspec.yamlfile.name: ecommerce_app description: A Flutter eCommerce application with GetX. publish_to: 'none' environment: sdk: ">=2.17.0 <3.0.0" dependencies: flutter: sdk: flutter get: ^4.6.5 http: ^0.13.5 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true assets: - assets/images/Notes:
- get: For state management and routing.
- http: To handle HTTP requests.
- assets/images/: Folder to store product images.
Models
Product Model
Create a
Productmodel to parse the JSON data from the server.File:
lib/models/product.dartimport 'dart:convert'; class Product { final String name; final String description; final String brand; final List<String> categories; final Map<String, String> 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; 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, }); factory Product.fromJson(Map<String, dynamic> json) { return Product( name: json['name'], description: json['description'], brand: json['brand'], categories: List<String>.from(json['categories']), hierarchicalCategories: Map<String, String>.from(json['hierarchicalCategories']), type: json['type'], price: json['price'].toDouble(), priceRange: json['price_range'], image: json['image'], url: json['url'], freeShipping: json['free_shipping'], popularity: json['popularity'], rating: json['rating'], objectID: json['objectID'], ); } static List<Product> listFromJson(String jsonData) { final data = json.decode(jsonData) as List; return data.map((item) => Product.fromJson(item)).toList(); } }
Controllers
Home Controller
The
HomeControllerwill manage fetching data from the server and providing it to the UI.File:
lib/controllers/home_controller.dartimport 'package:get/get.dart'; import 'package:http/http.dart' as http; import '../models/product.dart'; class HomeController extends GetxController { var products = <Product>[].obs; var isLoading = true.obs; var errorMessage = ''.obs; @override void onInit() { super.onInit(); fetchProducts(); } Future<void> fetchProducts() async { try { isLoading(true); errorMessage(''); // Replace with your actual API endpoint final response = await http.get(Uri.parse('https://api.example.com/products')); if (response.statusCode == 200) { products.value = Product.listFromJson(response.body); } else { errorMessage('Failed to load products: ${response.statusCode}'); } } catch (e) { errorMessage('An error occurred: $e'); } finally { isLoading(false); } } }Notes:
- Replace
'https://api.example.com/products'with your actual API endpoint. - The controller handles loading states and error messages.
Views
Home Page
The home page displays products in a grid layout similar to Instagram posts.
File:
lib/views/home_page.dartimport 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../controllers/home_controller.dart'; import 'search_page.dart'; import 'widgets/product_card.dart'; class HomePage extends StatelessWidget { final HomeController homeController = Get.put(HomeController()); HomePage({Key? key}) : super(key: key); final List<BottomNavigationBarItem> bottomItems = [ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.search), label: 'Search', ), // Add more items if needed ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('E-Commerce Home'), ), body: Obx(() { if (homeController.isLoading.value) { return Center(child: CircularProgressIndicator()); } else if (homeController.errorMessage.isNotEmpty) { return Center(child: Text(homeController.errorMessage.value)); } else { return GridView.builder( padding: EdgeInsets.all(8.0), itemCount: homeController.products.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, // Two columns crossAxisSpacing: 8.0, mainAxisSpacing: 8.0, childAspectRatio: 0.75, // Adjust as needed ), itemBuilder: (context, index) { final product = homeController.products[index]; return ProductCard(product: product); }, ); } }), bottomNavigationBar: BottomNavigationBar( items: bottomItems, currentIndex: 0, // Home is selected onTap: (index) { if (index == 1) { Get.to(() => SearchPage()); } // Handle other indices if you have more items }, ), ); } }Notes:
- Uses
Obxto reactively update the UI based on the controller's state. - Displays a grid of
ProductCardwidgets. - Bottom navigation bar includes Home and Search; tapping Search navigates to the
SearchPage.
Search Page
A simple search page with a search bar centered on the screen.
File:
lib/views/search_page.dartimport 'package:flutter/material.dart'; import 'package:get/get.dart'; class SearchPage extends StatelessWidget { SearchPage({Key? key}) : super(key: key); final TextEditingController searchController = TextEditingController(); void performSearch(String query) { // Implement your search functionality here print('Searching for: $query'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search'), leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () => Get.back(), ), ), body: Center( child: Padding( padding: EdgeInsets.symmetric(horizontal: 16.0), child: TextField( controller: searchController, onSubmitted: performSearch, decoration: InputDecoration( hintText: 'Search products...', prefixIcon: Icon(Icons.search), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), ), ), textInputAction: TextInputAction.search, ), ), ), ); } }Notes:
- Currently, the search functionality is a placeholder (
performSearchfunction). You can integrate it with your backend or filter the existing products.
Product Card Widget
A reusable widget to display individual product details in the grid.
File:
lib/views/widgets/product_card.dartimport 'package:flutter/material.dart'; import '../../models/product.dart'; class ProductCard extends StatelessWidget { final Product product; const ProductCard({required this.product, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), elevation: 3, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Product Image Expanded( child: ClipRRect( borderRadius: BorderRadius.vertical(top: Radius.circular(10)), child: Image.asset( 'assets/${product.image}', fit: BoxFit.cover, width: double.infinity, errorBuilder: (context, error, stackTrace) { return Container( color: Colors.grey[200], child: Center( child: Icon(Icons.broken_image, size: 50, color: Colors.grey), ), ); }, ), ), ), // Product Details Padding( padding: EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Product Name Text( product.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(height: 4), // Price Text( '\$${product.price.toStringAsFixed(2)}', style: TextStyle(color: Colors.green[700], fontWeight: FontWeight.bold), ), SizedBox(height: 4), // Rating Row( children: List.generate(5, (index) { if (index < product.rating) { return Icon(Icons.star, size: 16, color: Colors.amber); } else { return Icon(Icons.star_border, size: 16, color: Colors.amber); } }), ), ], ), ), ], ), ); } }Notes:
- Displays the product image, name, price, and rating.
- Handles image loading errors by showing a placeholder icon.
- Assumes images are stored in
assets/images/. Adjust the path if necessary.
Main File
Set up the
main.dartfile to initialize the app with GetX routing.File:
lib/main.dartimport 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'views/home_page.dart'; void main() { runApp(ECommerceApp()); } class ECommerceApp extends StatelessWidget { ECommerceApp({Key? key}) : super(key: key); final ThemeData theme = ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ); @override Widget build(BuildContext context) { return GetMaterialApp( title: 'E-Commerce App', debugShowCheckedModeBanner: false, theme: theme, home: HomePage(), ); } }Notes:
- Uses
GetMaterialAppfrom GetX for routing and state management. - Sets
HomePageas the initial screen.
Assets Configuration
Ensure your images are correctly placed in the
assets/images/directory and declared inpubspec.yaml.Adding Images
Place your product images in the following directory:
assets/ └── images/ ├── 9514008.jpg └── 9522015.jpgNote: The images should match the paths specified in the
imagefield of your product JSON data (e.g.,"images/9514008.jpg"corresponds toassets/images/9514008.jpg).Updating
pubspec.yamlEnsure the
assetssection inpubspec.yamlincludes the images directory:flutter: assets: - assets/images/After adding assets, run:
flutter pub get
Mock Data for Testing
If you don't have an actual API endpoint, you can mock the GET request. Modify the
HomeControllerto use local JSON data.Modified
fetchProductsMethod:Future<void> fetchProducts() async { try { isLoading(true); errorMessage(''); // Mock JSON data final String response = ''' [ { "name": "Dell - 2-in-1 13.3\\" Touch-Screen Laptop - Intel Core i7 - 8GB Memory - 1TB Hard Drive - Silver Touch", "description": "Only at Best Buy Dell Convertible 2-in-1 Laptop...", "brand": "Dell", "categories": [ "Computers & Tablets", "Laptops", "All Laptops", "PC Laptops" ], "hierarchicalCategories": { "lvl0": "Computers & Tablets", "lvl1": "Computers & Tablets > Laptops", "lvl2": "Computers & Tablets > Laptops > All Laptops", "lvl3": "Computers & Tablets > Laptops > All Laptops > PC Laptops" }, "type": "Notebooks", "price": 899.99, "price_range": "500 - 2000", "image": "images/9514008.jpg", "url": "http://www.bestbuy.com/site/dell-2-in-1-13-3-touch-screen-laptop...", "free_shipping": true, "popularity": 7718, "rating": 4, "objectID": "9514008" }, { "name": "Dell - Inspiron 7000 Series 2-in-1 15.6\\" Touch-Screen Laptop - Intel Core i5 - 8GB Memory - 500GB Hard Drive - Foggy Night", "description": "Only at Best Buy Dell Inspiron 7000 Series Convertible...", "brand": "Dell", "categories": [ "Computers & Tablets", "Laptops", "All Laptops", "PC Laptops" ], "hierarchicalCategories": { "lvl0": "Computers & Tablets", "lvl1": "Computers & Tablets > Laptops", "lvl2": "Computers & Tablets > Laptops > All Laptops", "lvl3": "Computers & Tablets > Laptops > All Laptops > PC Laptops" }, "type": "Notebooks", "price": 729.99, "price_range": "500 - 2000", "image": "images/9522015.jpg", "url": "http://www.bestbuy.com/site/dell-inspiron-7000-series-2-in-1...", "free_shipping": false, "popularity": 7695, "rating": 5, "objectID": "9522015" } ] '''; // Simulate network delay await Future.delayed(Duration(seconds: 2)); products.value = Product.listFromJson(response); } catch (e) { errorMessage('An error occurred: $e'); } finally { isLoading(false); } }Notes:
- This mock data allows you to test the UI without a real backend.
- Uncomment or comment out the actual HTTP request based on your needs.
Running the Application
-
Ensure all dependencies are installed:
flutter pub get -
Run the app:
flutter run
Expected Behavior:
- The home page displays a grid of products with images, names, prices, and ratings.
- A bottom navigation bar with Home and Search icons is present.
- Tapping the Search icon navigates to the Search page with a centered search bar.
Additional Enhancements
To further enhance the application, consider implementing the following features:
- Product Detail Page: Tap on a product to view detailed information.
- Search Functionality: Implement actual search queries against your product data.
- Bottom Navigation Bar: Add more navigation items like Cart, Profile, etc.
- State Management: Expand controllers to handle carts, user authentication, etc.
- Responsive Design: Ensure the UI looks good on various screen sizes.
- Error Handling: Improve error messages and handle edge cases gracefully.
Conclusion
This guide provides a foundational structure for building an eCommerce home page in Flutter using the GetX package. By organizing your code into models, controllers, and views, you ensure scalability and maintainability. Customize and expand upon this foundation to create a robust and feature-rich eCommerce application.