Skip to content

Instantly share code, notes, and snippets.

@oluyoung
Created April 27, 2024 06:38
Show Gist options
  • Save oluyoung/2e690b3951c27e7ea1fc6b18587c73cd to your computer and use it in GitHub Desktop.
Save oluyoung/2e690b3951c27e7ea1fc6b18587c73cd to your computer and use it in GitHub Desktop.
Generated code from pixels2flutter.dev
import 'package:flutter/material.dart';
import 'dart:convert';
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;
Map<String, bool> 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 toggleCart(String id) {
setState(() {
cart[id] = !(cart[id] ?? false);
});
}
int getCartCount() {
return cart.values.where((added) => added).length;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: FutureBuilder<Vehicle>(
future: fetchVehicleInfo(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Text('${snapshot.data!.year} ${snapshot.data!.brand} ${snapshot.data!.model} ${snapshot.data!.trim}');
} else {
return Text('Vehicle Info');
}
} else {
return CircularProgressIndicator();
}
},
),
actions: [
Stack(
alignment: Alignment.center,
children: [
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
// Navigate to cart page or show cart summary
},
),
Positioned(
right: 8,
top: 8,
child: Container(
padding: EdgeInsets.all(2),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: BoxConstraints(
minWidth: 14,
minHeight: 14,
),
child: Text(
'${getCartCount()}',
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
),
),
],
),
],
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
decoration: InputDecoration(
hintText: 'Search car parts',
prefixIcon: Icon(Icons.search),
),
onChanged: (value) {
// Implement search functionality
},
),
),
Expanded(
child: FutureBuilder<List<Product>>(
future: products,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.8,
),
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final product = snapshot.data![index];
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,
),
),
Text('\$${product.price}'),
if (product.inStock > 0)
Text('In stock: ${product.inStock}')
else
Text(
'Out of stock',
style: TextStyle(color: Colors.red),
),
SizedBox(height: 8),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: cart[product.id] ?? false ? Colors.transparent : Colors.green,
onPrimary: cart[product.id] ?? false ? Colors.red : Colors.white,
),
onPressed: () {
toggleCart(product.id);
},
child: Text(
cart[product.id] ?? false ? 'Remove' : 'Add to cart',
),
),
],
),
),
],
),
);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
}
return 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 is a placeholder for fetching vehicle information.
// Replace with actual HTTP request as needed.
return Vehicle(year: '2013', brand: 'Hyundai', model: 'Verna', trim: 'i3');
}
}
class Product {
final String id;
final String name;
final double price;
final String imageUrl;
final int inStock;
Product({
required this.id,
required this.name,
required this.price,
required this.imageUrl,
required this.inStock,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
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