resources changes

master
gitadmin 2 months ago
parent c664967fa2
commit ebe650103f

@ -1,9 +1,8 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/resources/drivers_model.dart';
import 'employees.dart';
class ResourcesDriverScreen extends StatefulWidget {
const ResourcesDriverScreen({super.key});
@ -13,21 +12,82 @@ class ResourcesDriverScreen extends StatefulWidget {
}
class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
// ---------- screen state ----------
int selectedTab = 1; // default "Drivers"
String search = '';
bool isLoading = false;
bool isLoading = false;
List<DriversModel> driversList = [];
// ---------- form (bottom sheet) ----------
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// Text controllers
final _nameCtrl = TextEditingController();
final _mobileCtrl = TextEditingController();
final _altMobileCtrl = TextEditingController();
final _locationCtrl = TextEditingController();
// Unused in UI but kept if you later need them
final _commissionCtrl = TextEditingController();
final _joinDateCtrl = TextEditingController();
// Dropdown state
String? _status; // 'available' | 'on delivery' | 'offline'
final List<String> _statusOptions = const ['available', 'on delivery', 'offline'];
String? selectedLicense;
final List<String> licenseNumbers = const [
'DL-042019-9876543',
'DL-052020-1234567',
'DL-072021-7654321',
];
String? selectedExperience; // years as string
final List<String> yearOptions = List<String>.generate(41, (i) => '$i'); // 0..40
String? _required(String? v, {String field = "This field"}) {
if (v == null || v.trim().isEmpty) return "$field is required";
return null;
}
String? _validatePhone(String? v, {String label = "Phone"}) {
if (v == null || v.trim().isEmpty) return "$label is required";
if (v.trim().length != 10) return "$label must be 10 digits";
return null;
}
@override
void initState() {
// TODO: implement initState
super.initState();
_fetchDrivers();
}
@override
void dispose() {
_nameCtrl.dispose();
_mobileCtrl.dispose();
_altMobileCtrl.dispose();
_locationCtrl.dispose();
_commissionCtrl.dispose();
_joinDateCtrl.dispose();
super.dispose();
}
void _resetForm() {
_formKey.currentState?.reset();
_nameCtrl.clear();
_mobileCtrl.clear();
_altMobileCtrl.clear();
_locationCtrl.clear();
_commissionCtrl.clear();
_joinDateCtrl.clear();
selectedLicense = null;
selectedExperience = null;
_status = null;
}
Future<void> _fetchDrivers() async {
setState(() => isLoading = true);
try {
final response = await AppSettings.getDrivers();
final data = (jsonDecode(response)['data'] as List)
@ -39,35 +99,283 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
isLoading = false;
});
} catch (e) {
debugPrint("⚠️ Error fetching orders: $e");
debugPrint("⚠️ Error fetching drivers: $e");
setState(() => isLoading = false);
}
}
// ---------- submit ----------
Future<void> _addDriver() async {
// run all validators, including the dropdowns
final ok = _formKey.currentState?.validate() ?? false;
if (!ok) {
setState(() {}); // ensure error texts render
return;
}
// Build payload (adjust keys to your API if needed)
final payload = <String, dynamic>{
"Name": _nameCtrl.text.trim(),
"license_number": selectedLicense ?? "",
"address": _locationCtrl.text.trim().isEmpty ? AppSettings.userAddress : _locationCtrl.text.trim(),
"supplier_name": AppSettings.userName,
"phone": _mobileCtrl.text.trim(),
"alternativeContactNumber": _altMobileCtrl.text.trim(),
"years_of_experience": selectedExperience ?? "",
"status": _status ?? "available",
};
final List<Map<String, dynamic>> drivers = [
{
'name': 'Ravi Kumar',
'status': 'available',
'location': 'Gandipet',
'deliveries': 134,
'commission': '₹500/day',
},
{
'name': 'Ravi Kumar',
'status': 'offline',
'location': 'Gandipet',
'deliveries': 134,
'commission': '₹500/day',
},
];
try {
final bool created = await AppSettings.addDrivers(payload);
if (!mounted) return;
if (created) {
AppSettings.longSuccessToast("Driver created successfully");
Navigator.pop(context, true); // close sheet
_resetForm();
_fetchDrivers(); // refresh
} else {
AppSettings.longFailedToast("Driver creation failed");
}
} catch (e) {
debugPrint("⚠️ addDrivers error: $e");
if (!mounted) return;
AppSettings.longFailedToast("Something went wrong");
}
}
// ---------- bottom sheet ----------
void _openDriverFormSheet(BuildContext context) {
_resetForm(); // fresh form every time
showModalBottomSheet(
context: context,
isScrollControlled: true, // allow content to move for keyboard
backgroundColor: Colors.transparent, // style inner container
builder: (context) {
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
return FractionallySizedBox(
heightFactor: 0.75, // fixed height (75% of screen)
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Padding(
padding: EdgeInsets.fromLTRB(20, 16, 20, 20 + bottomInset),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Handle + close (optional, simple close icon)
Row(
children: [
Expanded(
child: Center(
child: Container(
width: 36,
height: 4,
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(
color: const Color(0xFFE0E0E0),
borderRadius: BorderRadius.circular(2),
),
),
),
),
IconButton(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.close),
),
],
),
_LabeledField(
label: "Driver Name *",
child: TextFormField(
controller: _nameCtrl,
validator: (v) => _required(v, field: "Driver Name"),
decoration: InputDecoration(
hintText: "Full Name",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
_LabeledField(
label: "Driver License Number *",
child: DropdownButtonFormField<String>(
value: selectedLicense,
items: licenseNumbers
.map((t) => DropdownMenuItem(value: t, child: Text(t)))
.toList(),
onChanged: (v) => setState(() => selectedLicense = v),
validator: (v) => v == null || v.isEmpty ? "Driver License required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Select License Number",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: Image.asset('images/downarrow.png', width: 16, height: 16),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
_LabeledField(
label: "Years of Experience *",
child: DropdownButtonFormField<String>(
value: selectedExperience,
items: yearOptions
.map((t) => DropdownMenuItem(value: t, child: Text(t)))
.toList(),
onChanged: (v) => setState(() => selectedExperience = v),
validator: (v) => v == null || v.isEmpty ? "Experience is required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Years",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: Image.asset('images/downarrow.png', width: 16, height: 16),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
_LabeledField(
label: "Phone Number *",
child: TextFormField(
controller: _mobileCtrl,
validator: (v) => _validatePhone(v, label: "Phone Number"),
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(10),
],
decoration: InputDecoration(
hintText: "Mobile Number",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
_LabeledField(
label: "Alternate Phone Number",
child: TextFormField(
controller: _altMobileCtrl,
validator: (v) {
if (v == null || v.trim().isEmpty) return null; // optional
return _validatePhone(v, label: "Alternate Phone Number");
},
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(10),
],
decoration: InputDecoration(
hintText: "Mobile Number",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
_LabeledField(
label: "Location *",
child: TextFormField(
controller: _locationCtrl,
validator: (v) => _required(v, field: "Location"),
decoration: InputDecoration(
hintText: "Area / locality",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.done,
),
),
_LabeledField(
label: "Status *",
child: DropdownButtonFormField<String>(
value: _status,
items: _statusOptions
.map((s) => DropdownMenuItem(value: s, child: Text(s)))
.toList(),
onChanged: (v) => setState(() => _status = v),
validator: (v) => v == null || v.isEmpty ? "Status is required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Select status",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: const Icon(Icons.keyboard_arrow_down_rounded),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF8270DB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
),
onPressed: _addDriver,
child: Text(
"Save",
style: fontTextStyle(14, Colors.white, FontWeight.w600),
),
),
),
],
),
),
),
),
),
);
},
);
}
// ---------- UI ----------
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
// Top card
Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.all(14),
@ -90,27 +398,20 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset('images/drivers.png',
fit: BoxFit.contain),
child: Image.asset('images/drivers.png', fit: BoxFit.contain),
),
),
const SizedBox(height: 8),
Text('Total Drivers',
style: fontTextStyle(
12, const Color(0xFF2D2E30), FontWeight.w500)),
Text('Total Drivers', style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500)),
],
),
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text('${driversList.length.toString()}',
style: fontTextStyle(
24, const Color(0xFF0D3771), FontWeight.w500)),
Text(driversList.length.toString(), style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500)),
const SizedBox(height: 6),
Text('+1 since last month',
style: fontTextStyle(
10, const Color(0xFF646566), FontWeight.w400)),
Text('+1 since last month', style: fontTextStyle(10, const Color(0xFF646566), FontWeight.w400)),
],
),
],
@ -123,11 +424,9 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
child: IntrinsicHeight(
child: Row(
children: const [
Expanded(
child: SmallMetricBox(title: 'On delivery', value: '2')),
Expanded(child: SmallMetricBox(title: 'On delivery', value: '2')),
SizedBox(width: 8),
Expanded(
child: SmallMetricBox(title: 'Available', value: '3')),
Expanded(child: SmallMetricBox(title: 'Available', value: '3')),
SizedBox(width: 8),
Expanded(child: SmallMetricBox(title: 'Offline', value: '1')),
],
@ -137,7 +436,7 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
const SizedBox(height: 12),
// Gray background with search and list
// Search + list
Expanded(
child: Container(
color: const Color(0xFFF5F5F5),
@ -149,29 +448,24 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
children: [
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(
color: const Color(0xFF939495), width: 0.5),
border: Border.all(color: const Color(0xFF939495), width: 0.5),
borderRadius: BorderRadius.circular(22),
),
child: Row(
children: [
Image.asset('images/search.png',
width: 18, height: 18),
Image.asset('images/search.png', width: 18, height: 18),
const SizedBox(width: 8),
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: 'Search',
hintStyle: fontTextStyle(12,
Color(0xFF939495), FontWeight.w400),
hintStyle: fontTextStyle(12, const Color(0xFF939495), FontWeight.w400),
border: InputBorder.none,
isDense: true,
),
onChanged: (v) =>
setState(() => search = v),
onChanged: (v) => setState(() => search = v),
),
),
],
@ -179,18 +473,16 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
),
),
const SizedBox(width: 16),
Image.asset("images/icon_tune.png",
width: 24, height: 24),
Image.asset("images/icon_tune.png", width: 24, height: 24),
const SizedBox(width: 16),
Image.asset("images/up_down arrow.png",
width: 24, height: 24),
Image.asset("images/up_down arrow.png", width: 24, height: 24),
],
),
const SizedBox(height: 12),
// Driver list
Expanded(
child: ListView.separated(
child: isLoading
? const Center(child: CircularProgressIndicator())
: ListView.separated(
itemCount: driversList.length,
separatorBuilder: (_, __) => const SizedBox(height: 12),
itemBuilder: (context, idx) {
@ -199,7 +491,7 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
name: d.driver_name,
status: d.status,
location: d.address,
deliveries: int.parse(d.deliveries),
deliveries: int.tryParse(d.deliveries) ?? 0,
commission: d.commision,
);
},
@ -213,21 +505,9 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
],
),
// Floating Action Button
// FAB -> open fixed-height form sheet
floatingActionButton: FloatingActionButton(
onPressed: () async{
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FleetEmployees(),
),
);
// If result indicates API reload
if (result == true) {
_fetchDrivers();
}
},
onPressed: () => _openDriverFormSheet(context),
backgroundColor: Colors.black,
shape: const CircleBorder(),
child: const Icon(Icons.add, color: Colors.white),
@ -236,7 +516,8 @@ class _ResourcesDriverScreenState extends State<ResourcesDriverScreen> {
}
}
// Metric Box widget
// ---------- widgets ----------
class SmallMetricBox extends StatelessWidget {
final String title;
final String value;
@ -255,20 +536,15 @@ class SmallMetricBox extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style:
fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500)),
Text(title, style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500)),
const SizedBox(height: 4),
Text(value,
style:
fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500)),
Text(value, style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500)),
],
),
);
}
}
// Driver Card widget
class DriverCard extends StatelessWidget {
final String name;
final String status;
@ -287,6 +563,9 @@ class DriverCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final statusColor =
status == "available" ? Colors.green : (status == "on delivery" ? Colors.orange : Colors.grey);
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
@ -304,52 +583,33 @@ class DriverCard extends StatelessWidget {
Row(
children: [
ClipOval(
child: Image.asset("images/profile_pic.png",
height: 36, width: 36, fit: BoxFit.cover),
child: Image.asset("images/profile_pic.png", height: 36, width: 36, fit: BoxFit.cover),
),
const SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name,
style: fontTextStyle(
14, const Color(0xFF2D2E30), FontWeight.w500)),
Text(name, style: fontTextStyle(14, const Color(0xFF2D2E30), FontWeight.w500)),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: status == "available"
? Colors.green
: Colors.grey,
),
),
child: Text(
status,
style: fontTextStyle(
10,
status == "available" ? Colors.green : Colors.grey,
FontWeight.w400,
),
border: Border.all(color: statusColor),
),
child: Text(status, style: fontTextStyle(10, statusColor, FontWeight.w400)),
),
],
),
],
),
Container(
padding: const EdgeInsets.all(8), // spacing around the icon
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Color(0xFFF5F6F6), // background color
shape: BoxShape.circle, // makes it perfectly round
),
child: Image.asset(
"images/phone_icon.png",
width: 20,
height: 20,
color: Color(0xFFF5F6F6),
shape: BoxShape.circle,
),
child: Image.asset("images/phone_icon.png", width: 20, height: 20),
),
],
),
@ -360,13 +620,8 @@ class DriverCard extends StatelessWidget {
Text.rich(
TextSpan(
children: [
TextSpan(
text: "Location\n", style: fontTextStyle(8, Color(0xFF939495), FontWeight.w500,
),
),
TextSpan(
text: location, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w500,),
),
TextSpan(text: "Location\n", style: fontTextStyle(8, const Color(0xFF939495), FontWeight.w500)),
TextSpan(text: location, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w500)),
],
),
textAlign: TextAlign.center,
@ -374,64 +629,43 @@ class DriverCard extends StatelessWidget {
Text.rich(
TextSpan(
children: [
TextSpan(
text: "Deliveries\n", style: fontTextStyle(8, const Color(0xFF939495), FontWeight.w400,
),
),
TextSpan(
text: deliveries.toString(), style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w500,),
),
TextSpan(text: "Deliveries\n", style: fontTextStyle(8, const Color(0xFF939495), FontWeight.w400)),
TextSpan(text: deliveries.toString(), style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w500)),
],
),
textAlign: TextAlign.center,
),
// Commission
Text.rich(
TextSpan(
children: [
TextSpan(
text: "Commission\n", style: fontTextStyle(8, Color(0xFF939495), FontWeight.w400,
),
),
TextSpan(
text: commission, style: fontTextStyle(12, Color(0xFF515253), FontWeight.w500,),
),
TextSpan(text: "Commission\n", style: fontTextStyle(8, const Color(0xFF939495), FontWeight.w400)),
TextSpan(text: commission, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w500)),
],
),
textAlign: TextAlign.center,
),
],
),
const SizedBox(height: 12),
// Buttons row
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: Color(0xFF939495)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
onPressed: () {},
child: Text("View Schedule",
style: fontTextStyle(
12, Color(0xFF515253), FontWeight.w400)),
child: Text("View Schedule", style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w400)),
),
const SizedBox(width: 12),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF8270DB),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
onPressed: () {},
child: Text("Assign", style: fontTextStyle(12, Color(0xFFFFFFFF), FontWeight.w400)
),
child: Text("Assign", style: fontTextStyle(12, const Color(0xFFFFFFFF), FontWeight.w400)),
),
],
)
@ -440,3 +674,24 @@ class DriverCard extends StatelessWidget {
);
}
}
class _LabeledField extends StatelessWidget {
final String label;
final Widget child;
const _LabeledField({required this.label, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w600)),
const SizedBox(height: 6),
child,
],
),
);
}
}

@ -1,19 +1,15 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/resources/tankers_model.dart';
// Screens (single import each) keep if you actually navigate to these
import 'fleet.dart';
import 'resources_drivers.dart';
import 'resources_sources.dart';
import 'package:supplier_new/resources/resources_drivers.dart';
import 'package:supplier_new/resources/resources_sources.dart';
import 'fleet.dart';void main() => runApp(const MaterialApp(home: ResourcesFleetScreen()));
void main() => runApp(const MaterialApp(home: ResourcesFleetScreen()));
class ResourcesFleetScreen extends StatefulWidget {
const ResourcesFleetScreen({super.key});
@ -25,13 +21,28 @@ class ResourcesFleetScreen extends StatefulWidget {
class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
final _formKey = GlobalKey<FormState>();
// Controllers
// Controllers (sheet)
final _nameCtrl = TextEditingController();
final _capacityCtrl = TextEditingController(); // hint-like
final _capacityCtrl = TextEditingController();
final _plateCtrl = TextEditingController();
final _mfgYearCtrl = TextEditingController();
final _insExpiryCtrl = TextEditingController();
// Dropdown selections (sheet)
String? selectedType;
String? selectedTypeOfWater;
// Dropdown options (adjust to your backend)
final List<String> tankerTypes = const [
"Standard Tanker",
"High-Capacity Tanker",
"Small Tanker",
];
final List<String> typeOfWater = const [
"Drinking water",
"Bore water",
];
String? _required(String? v, {String field = "This field"}) {
if (v == null || v.trim().isEmpty) return "$field is required";
return null;
@ -39,19 +50,27 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
int selectedTab = 0;
String search = '';
bool isLoading = false;
bool isLoading = false;
List<TankersModel> tankersList = [];
@override
void initState() {
// TODO: implement initState
super.initState();
_fetchTankers();
}
@override
void dispose() {
_nameCtrl.dispose();
_capacityCtrl.dispose();
_plateCtrl.dispose();
_mfgYearCtrl.dispose();
_insExpiryCtrl.dispose();
super.dispose();
}
Future<void> _fetchTankers() async {
setState(() => isLoading = true);
try {
final response = await AppSettings.getTankers();
final data = (jsonDecode(response)['data'] as List)
@ -63,207 +82,275 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
isLoading = false;
});
} catch (e) {
debugPrint("⚠️ Error fetching orders: $e");
debugPrint("⚠️ Error fetching tankers: $e");
setState(() => isLoading = false);
}
}
final List<Map<String, dynamic>> items = [
{
'title': 'Tanker Name',
'subtitle': 'Drinking water - 10,000 L',
'status': ['filled', 'available'],
'code': 'TS 07 J 3492',
'owner': 'Ramesh Krishna'
},
{
'title': 'Drinking Water - 15,000L',
'subtitle': 'Drinking water - 15,000 L',
'status': ['empty', 'available'],
'code': 'TS 07 J 3492',
'owner': 'Ramesh Krishna'
},
{
'title': 'Tanker Name',
'subtitle': 'Drinking water - 10,000 L',
'status': ['filled', 'in-use'],
'code': 'TS 07 J 3492',
'owner': 'Ramesh Krishna'
},
{
'title': 'Drinking Water - 15,000L',
'subtitle': 'Drinking water - 15,000 L',
'status': ['empty', 'in-use'],
'code': 'TS 07 J 3492',
'owner': 'Ramesh Krishna'
},
{
'title': 'Tanker Name',
'subtitle': 'Drinking water - 10,000 L',
'status': ['filled', 'maintenance'],
'code': 'TS 07 J 3492',
'owner': 'Ramesh Krishna'
},
];
Future<void> _pickInsuranceDate() async {
final picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
builder: (context, child) {
return Theme(
data: Theme.of(context).copyWith(
dialogBackgroundColor: Colors.white,
colorScheme: Theme.of(context).colorScheme.copyWith(
primary: const Color(0xFF8270DB),
surface: Colors.white,
onSurface: const Color(0xFF101214),
),
),
child: child!,
);
},
);
if (picked != null) {
final dd = picked.day.toString().padLeft(2, '0');
final mm = picked.month.toString().padLeft(2, '0');
final yyyy = picked.year.toString();
_insExpiryCtrl.text = "$dd-$mm-$yyyy";
setState(() {});
}
}
void _resetForm() {
_formKey.currentState?.reset();
_nameCtrl.clear();
_capacityCtrl.clear();
_plateCtrl.clear();
_mfgYearCtrl.clear();
_insExpiryCtrl.clear();
selectedType = null;
selectedTypeOfWater = null;
}
Future<void> _addTanker() async {
// Validate
final ok = _formKey.currentState?.validate() ?? false;
if (!ok) {
setState(() {}); // force rebuild to show errors
return;
}
// Build payload keys to match your backend
final payload = <String, dynamic>{
"tankerName": _nameCtrl.text.trim(),
"capacity": _capacityCtrl.text.trim(),
"typeofwater": selectedTypeOfWater ?? "",
"supplier_address": AppSettings.userAddress,
"supplier_name": AppSettings.userName,
"phoneNumber": AppSettings.phoneNumber,
"tanker_type": selectedType ?? "",
"license_plate": _plateCtrl.text.trim(),
"manufacturing_year": _mfgYearCtrl.text.trim(),
"insurance_exp_date": _insExpiryCtrl.text.trim(),
};
try {
final bool tankStatus = await AppSettings.addTankers(payload);
if (!mounted) return;
if (tankStatus) {
AppSettings.longSuccessToast("Tanker Created Successfully");
Navigator.pop(context, true); // close sheet
_resetForm();
_fetchTankers(); // refresh from server
} else {
AppSettings.longFailedToast("Tanker Creation failed");
}
} catch (e) {
debugPrint("⚠️ addTankers error: $e");
if (!mounted) return;
AppSettings.longFailedToast("Something went wrong");
}
}
void openTankerSimpleSheet(BuildContext context) {
_resetForm(); // open fresh
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
backgroundColor: Colors.transparent,
builder: (context) {
return Padding(
padding: EdgeInsets.only(
left: 20,
right: 20,
top: 16,
bottom: MediaQuery.of(context).viewInsets.bottom + 20,
),
child: Form(
key: _formKey,
child: ListView(
shrinkWrap: true,
children: [
// Tanker Name
Text("Tanker Name *",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600)),
const SizedBox(height: 6),
TextFormField(
controller: _nameCtrl,
validator: (v) => _required(v, field: "Tanker Name"),
decoration: const InputDecoration(
hintText: "Enter Tanker Name",
border: OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
final viewInsets = MediaQuery.of(context).viewInsets.bottom;
return FractionallySizedBox(
heightFactor: 0.75,
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Padding(
padding: EdgeInsets.fromLTRB(20, 16, 20, 20 + viewInsets),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_LabeledField(
label: "Tanker Name *",
child: TextFormField(
controller: _nameCtrl,
validator: (v) => _required(v, field: "Tanker Name"),
decoration: InputDecoration(
hintText: "Enter Tanker Name",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
// Capacity
Text("Tanker Capacity (in L) *",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600)),
const SizedBox(height: 6),
TextFormField(
controller: _capacityCtrl,
validator: (v) => _required(v, field: "Tanker Capacity"),
decoration: InputDecoration(
hintText: "10,000 L",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9,]')),
],
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
_LabeledField(
label: "Tanker Capacity (in L) *",
child: TextFormField(
controller: _capacityCtrl,
validator: (v) => _required(v, field: "Tanker Capacity"),
decoration: InputDecoration(
hintText: "10,000",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9,]')),
],
textInputAction: TextInputAction.next,
),
),
// License Plate
Text("License Plate *",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600)),
const SizedBox(height: 6),
TextFormField(
controller: _plateCtrl,
validator: (v) => _required(v, field: "License Plate"),
decoration: InputDecoration(
hintText: "AB 05 H 4948",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textCapitalization: TextCapitalization.characters,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
_LabeledField(
label: "Tanker Type *",
child: DropdownButtonFormField<String>(
value: selectedType,
items: tankerTypes
.map((t) => DropdownMenuItem(value: t, child: Text(t)))
.toList(),
onChanged: (v) => setState(() => selectedType = v),
validator: (v) => v == null || v.isEmpty ? "Tanker Type is required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Select Type",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: Image.asset('images/downarrow.png', width: 16, height: 16),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
// Manufacturing Year (optional)
Text("Manufacturing Year (opt)",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600)),
const SizedBox(height: 6),
TextFormField(
controller: _mfgYearCtrl,
decoration: InputDecoration(
hintText: "YYYY",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(4),
],
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
_LabeledField(
label: "Type of water *",
child: DropdownButtonFormField<String>(
value: selectedTypeOfWater,
items: typeOfWater
.map((t) => DropdownMenuItem(value: t, child: Text(t)))
.toList(),
onChanged: (v) => setState(() => selectedTypeOfWater = v),
validator: (v) => v == null || v.isEmpty ? "Type of water is required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Select type of water",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: Image.asset('images/downarrow.png', width: 16, height: 16),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
// Insurance Expiry Date (optional)
Text("Insurance Expiry Date (opt)",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600)),
const SizedBox(height: 6),
TextFormField(
controller: _insExpiryCtrl,
readOnly: true,
decoration: InputDecoration(
hintText: "DD-MM-YYYY",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
suffixIcon: const Icon(Icons.calendar_today_outlined, size: 18),
),
onTap: () async {
final now = DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: now,
firstDate: DateTime(now.year - 30),
lastDate: DateTime(now.year + 30),
);
if (picked != null) {
final dd = picked.day.toString().padLeft(2, '0');
final mm = picked.month.toString().padLeft(2, '0');
final yyyy = picked.year.toString();
_insExpiryCtrl.text = "$dd-$mm-$yyyy";
}
},
),
const SizedBox(height: 20),
_LabeledField(
label: "License Plate *",
child: TextFormField(
controller: _plateCtrl,
validator: (v) => _required(v, field: "License Plate"),
decoration: InputDecoration(
hintText: "AB 05 H 4948",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textCapitalization: TextCapitalization.characters,
textInputAction: TextInputAction.next,
),
),
// Save button
SizedBox(
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF8270DB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
_LabeledField(
label: "Manufacturing Year (opt)",
child: TextFormField(
controller: _mfgYearCtrl,
decoration: InputDecoration(
hintText: "YYYY",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(4),
],
textInputAction: TextInputAction.next,
),
),
),
onPressed: () async {
if (_formKey.currentState?.validate() != true) return;
// TODO: Replace with your save logic / API call
// Example:
// final ok = await saveTanker();
// if (ok) Navigator.pop(context, true);
Navigator.pop(context, true); // close sheet on success
},
child: Text(
"Save",
style: fontTextStyle(14, Colors.white, FontWeight.w600),
),
_LabeledField(
label: "Insurance Expiry Date (opt)",
child: TextFormField(
controller: _insExpiryCtrl,
readOnly: true,
decoration: InputDecoration(
hintText: "DD-MM-YYYY",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
suffixIcon: const Icon(Icons.calendar_today_outlined, size: 18),
),
onTap: _pickInsuranceDate,
),
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF8270DB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
),
onPressed: _addTanker,
child: Text(
"Save",
style: fontTextStyle(14, Colors.white, FontWeight.w600),
),
),
),
],
),
),
],
),
),
),
);
@ -271,8 +358,6 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
);
}
@override
Widget build(BuildContext context) {
final filtered = tankersList.where((it) {
@ -285,6 +370,7 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
backgroundColor: Colors.white,
body: Column(
children: [
// Header section
Container(
color: Colors.white,
padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
@ -297,7 +383,7 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Color(0xFF939495)),
border: Border.all(color: const Color(0xFF939495)),
),
child: Row(
children: [
@ -309,56 +395,47 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
height: 40,
decoration: const BoxDecoration(
color: Color(0xFFF6F0FF),
borderRadius:
BorderRadius.all(Radius.circular(8)),
borderRadius: BorderRadius.all(Radius.circular(8)),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
'images/truck.png',
fit: BoxFit.contain,
),
child: Image.asset('images/truck.png', fit: BoxFit.contain),
),
),
const SizedBox(height: 8),
Text('Total Tankers', style: fontTextStyle(12, Color(0xFF2D2E30), FontWeight.w500, // or w500 if you want slightly bolder
),
Text('Total Tankers',
style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500),
),
],
),
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [Text(tankersList.length.toString(), style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500,
),
children: [
Text(
tankersList.length.toString(),
style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500),
),
SizedBox(height: 6),
const SizedBox(height: 6),
Text('+2 since last month',
style: fontTextStyle(10, Color(0xFF646566), FontWeight.w400,)),
style: fontTextStyle(10, const Color(0xFF646566), FontWeight.w400),
),
],
),
],
),
),
const SizedBox(height: 12),
IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: SmallMetricBox(title: 'Active', value: '2')),
const SizedBox(width: 8),
Expanded(
child: SmallMetricBox(title: 'Inactive', value: '3')),
const SizedBox(width: 8),
Expanded(
child: SmallMetricBox(
title: 'Under Maintenances', value: '1')),
children: const [
Expanded(child: SmallMetricBox(title: 'Active', value: '2')),
SizedBox(width: 8),
Expanded(child: SmallMetricBox(title: 'Inactive', value: '3')),
SizedBox(width: 8),
Expanded(child: SmallMetricBox(title: 'Under Maintenance', value: '1')),
],
),
),
@ -366,10 +443,10 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
),
),
// -------- SECOND SECTION (gray background) ----------
// List section
Expanded(
child: Container(
color: const Color(0xFFF5F5F5), // Gray background
color: const Color(0xFFF5F5F5),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column(
@ -379,13 +456,9 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
SizedBox(
width: 270,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(
color: Color(0xFF939495), // 👈 border color
width: 0.5, // 👈 border width
),
border: Border.all(color: const Color(0xFF939495), width: 0.5),
borderRadius: BorderRadius.circular(22),
),
child: Row(
@ -395,8 +468,9 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
height: 20,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/search.png'),
fit: BoxFit.contain),
image: AssetImage('images/search.png'),
fit: BoxFit.contain,
),
),
),
const SizedBox(width: 8),
@ -404,15 +478,11 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
child: TextField(
decoration: InputDecoration(
hintText: 'Search',
hintStyle: fontTextStyle(
12,
const Color(0xFF939495),
FontWeight.w400),
hintStyle: fontTextStyle(12, const Color(0xFF939495), FontWeight.w400),
border: InputBorder.none,
isDense: true,
),
onChanged: (v) =>
setState(() => search = v),
onChanged: (v) => setState(() => search = v),
),
),
],
@ -425,8 +495,9 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
height: 24,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/icon_tune.png'),
fit: BoxFit.contain),
image: AssetImage('images/icon_tune.png'),
fit: BoxFit.contain,
),
),
),
const SizedBox(width: 16),
@ -435,18 +506,18 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
height: 24,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/up_down arrow.png'),
fit: BoxFit.contain),
image: AssetImage('images/up_down_arrow.png'),
fit: BoxFit.contain,
),
),
),
],
),
const SizedBox(height: 12),
// Cards List
Expanded(
child: ListView.separated(
child: isLoading
? const Center(child: CircularProgressIndicator())
: ListView.separated(
itemCount: filtered.length,
separatorBuilder: (_, __) => const SizedBox(height: 10),
itemBuilder: (context, idx) {
@ -470,24 +541,10 @@ class _ResourcesFleetScreenState extends State<ResourcesFleetScreen> {
],
),
floatingActionButton: FloatingActionButton(
onPressed: () async{
openTankerSimpleSheet(context);
/*final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FleetStep1Page(),
),
);
// If result indicates API reload
if (result == true) {
_fetchTankers();
}*/
},
onPressed: () => openTankerSimpleSheet(context),
backgroundColor: const Color(0xFF000000),
shape: const CircleBorder(), // ensures circle
child: const Icon(Icons.add,color: Colors.white,),
shape: const CircleBorder(),
child: const Icon(Icons.add, color: Colors.white),
),
);
}
@ -506,22 +563,22 @@ class SmallMetricBox extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Color(0xFF939495)),
border: Border.all(color: const Color(0xFF939495)),
color: Colors.white,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style:
fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500)),
Text(value,
style:
fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500)),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500),
),
Text(
value,
style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500),
),
],
),
);
@ -601,28 +658,23 @@ class TankCard extends StatelessWidget {
final chipTextColor = _chipTextColor(s);
return Container(
margin: const EdgeInsets.only(right: 6),
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _chipColor(s),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: chipTextColor, width: 1),
),
child: Text(
s, style:
fontTextStyle(10, chipTextColor, FontWeight.w400),
s,
style: fontTextStyle(10, chipTextColor, FontWeight.w400),
),
);
}).toList(),
),
const SizedBox(height: 8),
Text (title,
style: fontTextStyle(
14, const Color(0xFF343637), FontWeight.w600)),
Text(title, style: fontTextStyle(14, const Color(0xFF343637), FontWeight.w600)),
const SizedBox(height: 6),
Text(subtitle+' - '+capacity+' L',
style: fontTextStyle(
10, const Color(0xFF343637), FontWeight.w600)),
Text("$subtitle - $capacity L", style: fontTextStyle(10, const Color(0xFF343637), FontWeight.w600)),
const SizedBox(height: 10),
Row(
children: [
@ -633,20 +685,17 @@ class TankCard extends StatelessWidget {
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: (AppSettings.profilePictureUrl != '' &&
AppSettings.profilePictureUrl != 'null')
? NetworkImage(AppSettings.profilePictureUrl)
as ImageProvider
: const AssetImage("images/profile_pic.png"),
fit: BoxFit.cover),
image: (AppSettings.profilePictureUrl != '' && AppSettings.profilePictureUrl != 'null')
? NetworkImage(AppSettings.profilePictureUrl)
: const AssetImage("images/profile_pic.png") as ImageProvider,
fit: BoxFit.cover,
),
),
),
),
const SizedBox(width: 6),
Expanded(
child: Text(owner,
style: fontTextStyle(
8, const Color(0xFF646566), FontWeight.w400)),
child: Text(owner, style: fontTextStyle(8, const Color(0xFF646566), FontWeight.w400)),
),
],
),
@ -656,9 +705,7 @@ class TankCard extends StatelessWidget {
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(code,
style: fontTextStyle(
10, const Color(0xFF515253), FontWeight.w400)),
Text(code, style: fontTextStyle(10, const Color(0xFF515253), FontWeight.w400)),
const SizedBox(height: 28),
],
),
@ -667,3 +714,26 @@ class TankCard extends StatelessWidget {
);
}
}
// ====== Labeled Field Wrapper ======
class _LabeledField extends StatelessWidget {
final String label;
final Widget child;
const _LabeledField({required this.label, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w600)),
const SizedBox(height: 6),
child,
],
),
);
}
}

@ -1,13 +1,15 @@
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/resources/source_location.dart';
import 'package:supplier_new/resources/source_loctaions_model.dart';
import 'fleet.dart';
import 'resources_drivers.dart';
import 'resources_sources.dart';
// If you use the PlacePicker flow in the button below, make sure you have
// the needed imports in your project (google_maps_flutter, place_picker, etc).
// import 'package:google_maps_flutter/google_maps_flutter.dart';
// import 'package:place_picker/place_picker.dart';
// import 'package:location/location.dart';
void main() => runApp(const MaterialApp(home: ResourcesSourceScreen()));
@ -21,19 +23,60 @@ class ResourcesSourceScreen extends StatefulWidget {
class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
int selectedTab = 2;
String search = '';
bool isLoading = false;
bool isLoading = false;
List<SourceLocationsModel> sourceLocationsList = [];
// ---------- Form state (bottom sheet) ----------
final _formKey = GlobalKey<FormState>();
final _locationNameController = TextEditingController();
final _mobileCtrl = TextEditingController();
bool addBusinessAsSource = false; // toggle if you want to hide map input
String? selectedWaterType;
final List<String> waterTypes = const ['Drinking water', 'Bore water', 'Both'];
// Optional: values used by your map flow
// final location = Location(); // from 'location' package
// PickResult? selectedPlace;
double? lat;
double? lng;
String? address;
String? _required(String? v, {String field = "This field"}) {
if (v == null || v.trim().isEmpty) return "$field is required";
return null;
}
String? _validatePhone(String? v, {String label = "Phone"}) {
if (v == null || v.trim().isEmpty) return "$label is required";
if (v.trim().length != 10) return "$label must be 10 digits";
return null;
}
@override
void initState() {
// TODO: implement initState
super.initState();
_fetchDrivers();
_fetchSources();
}
Future<void> _fetchDrivers() async {
setState(() => isLoading = true);
@override
void dispose() {
_locationNameController.dispose();
_mobileCtrl.dispose();
super.dispose();
}
void _resetForm() {
_formKey.currentState?.reset();
_locationNameController.clear();
_mobileCtrl.clear();
selectedWaterType = null;
// keep address/lat/lng as last-picked unless you want to clear:
// address = null; lat = null; lng = null;
}
Future<void> _fetchSources() async {
setState(() => isLoading = true);
try {
final response = await AppSettings.getSourceLoctaions();
final data = (jsonDecode(response)['data'] as List)
@ -45,34 +88,299 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
isLoading = false;
});
} catch (e) {
debugPrint("⚠️ Error fetching orders: $e");
debugPrint("⚠️ Error fetching source locations: $e");
setState(() => isLoading = false);
}
}
final List<Map<String, dynamic>> items = [
{
'title': 'Gandipet Water Supply',
'subtitle': 'Road No.34, Blah',
},
{
'title': 'Gandipet Water Supply',
'subtitle': 'Road No.34, Blah',
},
{
'title': 'Gandipet Water Supply',
'subtitle': 'Road No.34, Blah',
},
{
'title': 'Gandipet Water Supply',
'subtitle': 'Road No.34, Blah',
},
{
'title': 'Gandipet Water Supply',
'subtitle': 'Road No.34, Blah',
},
];
Future<void> _addSourceLocation() async {
final ok = _formKey.currentState?.validate() ?? false;
if (addBusinessAsSource) {
// Use supplier's address as the source location
address = AppSettings.userAddress;
lat = AppSettings.supplierLatitude;
lng = AppSettings.supplierLongitude;
setState(() {});
}
if (!ok || selectedWaterType == null || selectedWaterType!.isEmpty) {
if (selectedWaterType == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Please select Water Type")),
);
}
setState(() {}); // ensure errors render
return;
}
final payload = <String, dynamic>{
"location_name": _locationNameController.text.trim(),
"phone": _mobileCtrl.text.trim(),
"water_type": selectedWaterType,
"status": 'active', // or whatever string your backend expects
"address": address,
"city": '',
"state": '',
"zip": '',
"latitude": lat,
"longitude": lng,
};
try {
final bool ok = await AppSettings.addSourceLocations(payload);
if (!mounted) return;
if (ok) {
AppSettings.longSuccessToast("Source location added successfully");
Navigator.pop(context, true); // close the sheet
_resetForm();
_fetchSources(); // refresh list
} else {
AppSettings.longFailedToast("Source location creation failed");
}
} catch (e) {
debugPrint("⚠️ addSourceLocations error: $e");
if (!mounted) return;
AppSettings.longFailedToast("Something went wrong");
}
}
void _openSourceFormSheet(BuildContext context) {
_resetForm(); // fresh form each time you open
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) {
final kbInset = MediaQuery.of(context).viewInsets.bottom;
return FractionallySizedBox(
heightFactor: 0.75, // fixed height
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Padding(
padding: EdgeInsets.fromLTRB(20, 16, 20, 20 + kbInset),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_LabeledField(
label: "Location Name *",
child: TextFormField(
controller: _locationNameController,
validator: (v) => _required(v, field: "Location Name"),
decoration: InputDecoration(
hintText: "Location Name",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
_LabeledField(
label: "Mobile Number *",
child: TextFormField(
controller: _mobileCtrl,
validator: (v) => _validatePhone(v, label: "Mobile Number"),
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(10),
],
decoration: InputDecoration(
hintText: "Mobile Number",
hintStyle: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
),
),
Visibility(
visible: !addBusinessAsSource,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
// Your PlacePicker flow goes here (kept commented for reference)
/*
location.serviceEnabled().then((value) {
if (value) {
initRenderer();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return PlacePicker(
resizeToAvoidBottomInset: false,
hintText: "Find a place ...",
searchingText: "Please wait ...",
selectText: "Select place",
outsideOfPickAreaText: "Place not in area",
initialPosition: kInitialPosition,
useCurrentLocation: true,
selectInitialPosition: true,
usePinPointingSearch: true,
usePlaceDetailSearch: true,
zoomGesturesEnabled: true,
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController controller) {},
onPlacePicked: (PickResult result) {
setState(() {
selectedPlace = result;
lat = selectedPlace!.geometry!.location.lat;
lng = selectedPlace!.geometry!.location.lng;
if (selectedPlace!.types!.length == 1) {
address = selectedPlace!.formattedAddress!;
} else {
address = '${selectedPlace!.name!}, ${selectedPlace!.formattedAddress!}';
}
Navigator.of(context).pop();
});
},
onMapTypeChanged: (MapType mapType) {},
apiKey: Platform.isAndroid ? APIKeys.androidApiKey : APIKeys.iosApiKey,
forceAndroidLocationManager: true,
);
},
),
);
} else {
showGeneralDialog(
context: context,
pageBuilder: (context, x, y) {
return Scaffold(
backgroundColor: Colors.grey.withOpacity(.5),
body: Center(
child: Container(
width: double.infinity,
height: 150,
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Please enable the location",
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text("Cancel"),
),
],
),
),
),
),
),
);
},
);
}
});
*/
},
icon: Image.asset('images/Add_icon.png', width: 16, height: 16),
label: Text(
"Add Location on map",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600),
),
),
),
const SizedBox(height: 12),
],
),
),
_LabeledField(
label: "Water Type *",
child: DropdownButtonFormField<String>(
value: selectedWaterType,
items: waterTypes
.map((w) => DropdownMenuItem(value: w, child: Text(w)))
.toList(),
onChanged: (v) => setState(() => selectedWaterType = v),
validator: (v) => v == null || v.isEmpty ? "Water Type is required" : null,
isExpanded: true,
alignment: Alignment.centerLeft,
hint: Text(
"Select Water Type",
style: fontTextStyle(14, const Color(0xFF939495), FontWeight.w400),
),
icon: Image.asset('images/downarrow.png', width: 16, height: 16),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 14),
),
),
),
const SizedBox(height: 20),
// Actions
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _addSourceLocation,
icon: Image.asset('images/Add_icon.png', width: 16, height: 16),
label: Text(
"Add Location",
style: fontTextStyle(14, const Color(0xFF646566), FontWeight.w600),
),
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF8270DB),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
),
onPressed: _addSourceLocation,
child: Text(
"Save",
style: fontTextStyle(14, Colors.white, FontWeight.w600),
),
),
),
],
),
],
),
),
),
),
),
);
},
);
}
// ---------- UI ----------
@override
Widget build(BuildContext context) {
final filtered = sourceLocationsList.where((it) {
@ -84,7 +392,6 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
// Top card section
@ -117,10 +424,7 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
'images/drivers.png',
fit: BoxFit.contain,
),
child: Image.asset('images/drivers.png', fit: BoxFit.contain),
),
),
const SizedBox(height: 8),
@ -136,7 +440,7 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${sourceLocationsList.length.toString()}',
sourceLocationsList.length.toString(),
style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500),
),
const SizedBox(height: 6),
@ -147,17 +451,15 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
],
),
),
const SizedBox(height: 12),
// Metrics boxes
IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
children: const [
Expanded(child: SmallMetricBox(title: 'Drinking water', value: '2')),
const SizedBox(width: 8),
SizedBox(width: 8),
Expanded(child: SmallMetricBox(title: 'Bore water', value: '3')),
const SizedBox(width: 8),
SizedBox(width: 8),
Expanded(child: SmallMetricBox(title: 'Both', value: '1')),
],
),
@ -166,7 +468,7 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
),
),
// SECOND SECTION (gray background)
// List section
Expanded(
child: Container(
color: const Color(0xFFF5F5F5),
@ -174,7 +476,6 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column(
children: [
// Search row
Row(
children: [
SizedBox(
@ -182,23 +483,12 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(
color: const Color(0xFF939495),
width: 0.5,
),
border: Border.all(color: const Color(0xFF939495), width: 0.5),
borderRadius: BorderRadius.circular(22),
),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/search.png'),
fit: BoxFit.contain),
),
),
Image.asset('images/search.png', width: 20, height: 20),
const SizedBox(width: 8),
Expanded(
child: TextField(
@ -216,33 +506,16 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
),
),
const SizedBox(width: 16),
Container(
width: 24,
height: 24,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/icon_tune.png'),
fit: BoxFit.contain),
),
),
Image.asset('images/icon_tune.png', width: 24, height: 24),
const SizedBox(width: 16),
Container(
width: 24,
height: 24,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('images/up_down arrow.png'),
fit: BoxFit.contain),
),
),
Image.asset('images/up_down arrow.png', width: 24, height: 24),
],
),
const SizedBox(height: 12),
// Cards List
Expanded(
child: ListView.separated(
child: isLoading
? const Center(child: CircularProgressIndicator())
: ListView.separated(
itemCount: filtered.length,
separatorBuilder: (_, __) => const SizedBox(height: 10),
itemBuilder: (context, idx) {
@ -261,19 +534,8 @@ class _ResourcesSourceScreenState extends State<ResourcesSourceScreen> {
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const HeroMode(
enabled: false,
child: SourceLocation(),
),
),
);
},
onPressed: () => _openSourceFormSheet(context),
backgroundColor: const Color(0xFF000000),
shape: const CircleBorder(),
child: const Icon(Icons.add, color: Colors.white),
@ -302,19 +564,23 @@ class SmallMetricBox extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500)),
Text(value,
style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500)),
Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500),
),
Text(
value,
style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500),
),
],
),
);
}
}
// ====== TankCard (with phone icon inside) ======
// ====== TankCard ======
class TankCard extends StatelessWidget {
final String title;
final String subtitle;
@ -336,35 +602,50 @@ class TankCard extends StatelessWidget {
),
child: Row(
children: [
// Title and subtitle
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: fontTextStyle(14, const Color(0xFF343637), FontWeight.w600)),
Text(title, style: fontTextStyle(14, const Color(0xFF343637), FontWeight.w600)),
const SizedBox(height: 6),
Text(subtitle,
style: fontTextStyle(10, const Color(0xFF515253), FontWeight.w600)),
Text(subtitle, style: fontTextStyle(10, const Color(0xFF515253), FontWeight.w600)),
],
),
),
const SizedBox(width: 8),
// Phone icon inside card
Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Color(0xFFF5F6F6),
shape: BoxShape.circle,
),
child: Image.asset(
"images/phone_icon.png",
width: 20,
height: 20,
),
child: Image.asset("images/phone_icon.png", width: 20, height: 20),
),
],
),
);
}
}
// ====== Labeled Field Wrapper ======
class _LabeledField extends StatelessWidget {
final String label;
final Widget child;
const _LabeledField({required this.label, required this.child});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: fontTextStyle(12, const Color(0xFF515253), FontWeight.w600)),
const SizedBox(height: 6),
child,
],
),
);
}
}

@ -490,6 +490,7 @@ class _SourceLocationState extends State<SourceLocation> {
// // SnackBar(content: Text("Saved ${_drivers.length} driver(s). Proceeding…")),
// // );
},
child: Text(
"Continue",
style: fontTextStyle(14, Colors.white, FontWeight.w400),

Loading…
Cancel
Save