0% found this document useful (0 votes)
4 views

Correctnewpage

This document defines a Flutter class that fetches inventory data from Firebase Firestore and displays it. The class streams inventory data, builds inventory items as cards with details like name, date created, remaining amount. It also shows a progress bar for used amount.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Correctnewpage

This document defines a Flutter class that fetches inventory data from Firebase Firestore and displays it. The class streams inventory data, builds inventory items as cards with details like name, date created, remaining amount. It also shows a progress bar for used amount.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import 'package:cloud_firestore/cloud_firestore.

dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

double globalRemainingAmount = 0.0; // Global variable for remaining amount

class NewPage extends StatefulWidget {


@override
_InventoryPageState createState() => _InventoryPageState();
}

class _InventoryPageState extends State<NewPage> {


late Stream<QuerySnapshot<Map<String, dynamic>>> _inventoryDataStream;
final FirebaseAuth _auth = FirebaseAuth.instance;

@override
void initState() {
super.initState();
_fetchInventoryDataStream();
}

void _fetchInventoryDataStream() {
_inventoryDataStream = FirebaseFirestore.instance
.collection('organicInputs')
.where('email', isEqualTo: _auth.currentUser?.email)
.snapshots();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.green[600],
title: Text('Inventory'),
),
body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: _inventoryDataStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (snapshot.data!.docs.isEmpty) {
return Center(child: Text('No inventory data available.'));
} else {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
final document = snapshot.data!.docs[index];
Map<String, dynamic>? data = document.data();
if (data != null &&
data['name'] != null &&
data['dateCreated'] != null &&
data['volume'] != null) {
return _buildInventoryItem(
data['name']!,
data['dateCreated'].toDate(),
data['volume']!,
document.id,
);
} else {
return SizedBox();
}
},
);
}
},
),
);
}

Widget _buildInventoryItem(
String name, DateTime dateCreated, String volume, String documentId) {
final double initialVolume = double.tryParse(volume) ?? 0.0;
double currentVolume = initialVolume;

return Card(
margin: EdgeInsets.symmetric(vertical: 8.0),
child: ListTile(
title: Text('Name: $name'),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Date Created: ${_formatDate(dateCreated)}'),
SizedBox(height: 8.0),
FutureBuilder<int>(
future: _fetchTotalAmountUsed(documentId),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return SizedBox();
} else {
int totalAmountUsed = snapshot.data ?? 0;
currentVolume = initialVolume - totalAmountUsed;
globalRemainingAmount =
currentVolume; // Set global remaining amount
final double remainingAmount =
currentVolume < 0 ? 0 : currentVolume;

// Calculate percentage for the bar graph


final double totalAmount = initialVolume;
final double usedPercentage =
((totalAmount - remainingAmount) / totalAmount) * 100;

return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Remaining Amount: ${remainingAmount.toStringAsFixed(1)}',
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 4.0),
Stack(
children: [
FractionallySizedBox(
alignment: Alignment.centerLeft,
widthFactor: 1.0,
child: Container(
height: 20.0,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(10.0),
),
),
),
FractionallySizedBox(
alignment: Alignment.centerRight,
widthFactor: usedPercentage / 100,
child: Container(
height: 20.0,
decoration: BoxDecoration(
color: Colors.grey[700],
borderRadius: BorderRadius.circular(10.0),
),
),
),
],
),
SizedBox(height: 8.0),
Text(
'Total Amount Used: $totalAmountUsed',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
);
}
},
),
],
),
),
);
}

Future<int> _fetchTotalAmountUsed(String documentId) async {


int totalAmountUsed = 0;
QuerySnapshot applicationsSnapshot = await FirebaseFirestore.instance
.collection('applications')
.where('organicInputId', isEqualTo: documentId)
.get();
for (QueryDocumentSnapshot doc in applicationsSnapshot.docs) {
int amount = doc['amount'] as int; // Convert to int
totalAmountUsed += amount;
}
return totalAmountUsed;
}

String _formatDate(DateTime date) {


return '${date.year}-${date.month}-${date.day}';
}
}

You might also like