Skip to content

Instantly share code, notes, and snippets.

@oluyoung
Created April 27, 2024 06:56
Show Gist options
  • Save oluyoung/5096cdac963ff46d00a04a2c86ce7acd to your computer and use it in GitHub Desktop.
Save oluyoung/5096cdac963ff46d00a04a2c86ce7acd to your computer and use it in GitHub Desktop.
Generated code from pixels2flutter.dev
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Auto Parts Dashboard',
theme: ThemeData(
primarySwatch: Colors.green,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: DashboardScreen(),
debugShowCheckedModeBanner: false,
);
}
}
class DashboardScreen extends StatefulWidget {
@override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
late Future<List<Product>> products;
Set<Product> cart = {};
@override
void initState() {
super.initState();
products = fetchProducts();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get(Uri.parse('http://192.168.1.13:3000/api/v1/public/products'));
if (response.statusCode == 200) {
List<dynamic> productsJson = json.decode(response.body);
return productsJson.map((json) => Product.fromJson(json)).toList();
} else {
throw Exception('Failed to load products');
}
}
void addToCart(Product product) {
setState(() {
if (cart.contains(product)) {
cart.remove(product);
} else {
cart.add(product);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: FutureBuilder<Vehicle>(
future: fetchVehicleInfo(), // Replace with actual data fetch
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Text('${snapshot.data!.year} ${snapshot.data!.brand} ${snapshot.data!.model} ${snapshot.data!.trim}');
} else {
return CircularProgressIndicator();
}
},
),
actions: [
Stack(
alignment: Alignment.topRight,
children: [
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
// Navigate to cart screen
},
),
if (cart.isNotEmpty)
CircleAvatar(
radius: 10.0,
backgroundColor: Colors.red,
child: Text(
cart.length.toString(),
style: TextStyle(color: Colors.white, fontSize: 12.0),
),
),
],
),
],
),
body: FutureBuilder<List<Product>>(
future: products,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return GridView.builder(
padding: EdgeInsets.all(8.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
childAspectRatio: 0.8,
),
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
Product product = snapshot.data![index];
return ProductCard(
product: product,
isInCart: cart.contains(product),
onAddToCart: () => addToCart(product),
);
},
);
} else if (snapshot.hasError) {
return Center(child: Text('Failed to load products'));
} else {
return Center(child: CircularProgressIndicator());
}
},
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.grid_view),
label: 'Categories',
),
BottomNavigationBarItem(
icon: Icon(Icons.history),
label: 'Order History',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Account',
),
],
),
);
}
Future<Vehicle> fetchVehicleInfo() async {
// This should be replaced with actual data fetch logic
return Vehicle(year: '2013', brand: 'Hyundai', model: 'Verna', trim: 'i3');
}
}
class ProductCard extends StatelessWidget {
final Product product;
final bool isInCart;
final VoidCallback onAddToCart;
const ProductCard({
Key? key,
required this.product,
required this.isInCart,
required this.onAddToCart,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Image.network(
product.imageUrl,
fit: BoxFit.contain,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
product.name,
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 4.0),
Text('\$${product.price.toStringAsFixed(2)}'),
SizedBox(height: 4.0),
if (product.inStock > 0)
Text('In stock: ${product.inStock}')
else
Text('Out of stock', style: TextStyle(color: Colors.red)),
SizedBox(height: 8.0),
ElevatedButton(
onPressed: onAddToCart,
child: Text(isInCart ? 'Remove' : 'Add to cart'),
style: ElevatedButton.styleFrom(
primary: isInCart ? Colors.transparent : Colors.green,
onPrimary: isInCart ? Colors.red : Colors.white,
side: isInCart ? BorderSide(color: Colors.red) : BorderSide.none,
),
),
],
),
),
],
),
);
}
}
class Product {
final String name;
final double price;
final String imageUrl;
final int inStock;
Product({
required this.name,
required this.price,
required this.imageUrl,
required this.inStock,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
name: json['name'],
price: json['price'].toDouble(),
imageUrl: json['imageUrl'],
inStock: json['inStock'],
);
}
}
class Vehicle {
final String year;
final String brand;
final String model;
final String trim;
Vehicle({
required this.year,
required this.brand,
required this.model,
required this.trim,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment